I am trying to replace the a text of a ul list using jQuery, but I am running into to issues. First the code only works if I click 'BTI' , and I need it to work right after the page opens, already tried .one and .ready . And second the code only replaces the text 'BTI' and it needs to do 'GIA' as well.
HTML :
<ul id="addition_membership_type-menu" class="ui-selectmenu-menu ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom w230 ui-selectmenu-open" aria-labelledby="addition_membership_type-button" role="listbox" aria-hidden="false" style="z-index: 9999; width: 230px; height: 250px; top: 1403.8px; left: 577px;" aria-disabled="false" aria-activedescendant="ui-selectmenu-item-517">
<li class="hide-from-ui-list" role="presentation">
<a id="" aria-selected="false" role="option" tabindex="-1" href="#">--- Please select ---</a>
</li>
<li class="" role="presentation">
<a aria-selected="false" role="option" tabindex="-1" href="#">BTI</a>
</li>
<li class="" role="presentation">
<a aria-selected="false" role="option" tabindex="-1" href="#">GIA</a>
</li>
</ul>
jQuery :
$('#addition_membership_type-menu li a').click(function(){
$(this).text(function(index, text) {
return text.replace('BTI', 'Baltic Miles');
return text.replace('GIA', 'G airline');
});
});
Thanks!
答案 0 :(得分:2)
1 - 您正在使用点击事件,因此它只会在点击时执行。将其更改为在dom ready($(function(){});
)
2 - 它只在点击的元素上运行,你必须遍历所有元素(.each
)
3 - 您使用了两个return语句,因此第二个语句从未到达。链接.replace
方法是一种可能的解决方案。
$(function(){
$('#addition_membership_type-menu li a').each(function(){
$(this).text($(this).text().replace('BTI', 'Baltic Miles').replace('GIA', 'G airline'));
});
});
答案 1 :(得分:0)
一个函数只能有一个return语句。在您点击一个return语句后,代码将离开该函数并停止执行。如果您想要它做多件事,请尝试
text.replace('BTI', 'Baltic Miles');
text.replace('GIA', 'G airline');
除非您要使用该值,否则您不需要返回值(例如,对输入添加两个的函数将返回2 +输入,以便您以后可以使用它。)
另外,请考虑使用window.onload = function ...
让它立即执行。
您的结束代码可能如下所示:
window.onload = function(index, text) {
$('#addition_membership_type-menu li a').replace('BTI', 'Baltic Miles');
$('#addition_membership_type-menu li a').replace('GIA', 'G airline');
});