我有这个显示/隐藏选择框(JS Fiddle),它从所选选项中获取一个类名,并隐藏相应的无序列表项。当点击某个选项时,我无法使用replace()
将文件Hide
替换为Show
,反之亦然。(例如,点击时显示月份应该变为隐藏月份。)
当我点击全部显示选项时,我还想将所有选项更改回Hide
。
我用的时候
findoption.replace('Hide','Show');
我收到此Uncaught TypeError: undefined is not a function
错误。任何人都可以告诉我该怎么做?任何帮助将不胜感激。
JS代码:
$(document).ready(function(){
$(".showhidelist").change(function() {
$this = $(this);
var findoption = $this.find('option:selected');
var selected = findoption.data('hide');
var show_hide_li = $("."+selected);
if (show_hide_li.css("display") == "none") {
show_hide_li.show();
/* Want to Replace the text Hide with Show */
}
else if (show_hide_li.is(':visible')){
show_hide_li.hide();
/* Want to Replace the text Show with Hide */
}
else if (selected == "Reset") {
$('li').show();
/* Want to Replace the text Show with Hide if it's true */
}
});
});
HTML
<select class="showhidelist">
<option data-hide="Reset">Show All</option>
<option data-hide="year">Hide Year</option>
<option data-hide="month">Hide Month</option>
<option data-hide="day">Hide Day</option>
</select>
<ul id="list">
<li class="year">2004</li>
<li class="month">Feb</li>
<li class="day">17</li>
<ul>
答案 0 :(得分:2)
您没有将text()
转换为替换版,您可以使用.text()替换文本的函数。
findoption.text(function(_,text){ return text.replace('Hide', 'Show')});
根据您的需要更改“隐藏”或“显示”一词。
更新:
我在里海评论中读到,您现在遇到的问题是您无法重新点击单击的选项,请尝试重新启动选择到第一个选项,如:
$(".showhidelist").prop('selectedIndex',0);
答案 1 :(得分:2)
findoption返回一个jquery数组,因此你需要访问那里的第一个元素。我认为以下内容将实现您所寻找的内容(就所选元素而言)。
findoption[0].innerHTML = findoption[0].innerHTML.replace('Show','Hide');
我不确定你在做什么 - 这有点古怪,因为你有显示/隐藏全部,你必须通过整个列表来更新它们。此外 - 当您重新选择已经选择的内容时,您没有获得选定的活动。
更新:这包括如何使用each()
jsfiddle:http://jsfiddle.net/hk4wg/15/