我在使用 jQuery 2.1.3 时遇到了奇怪的行为。当我替换列表中 anchor 元素中的文本时, anchor 将被删除。我怀疑这与我的选择器有关,但我不明白为什么。
选择器:
$("ul li:nth-child(2) a, ul li")
这个jsFiddle显示我的代码并演示奇怪的行为。
最佳答案
因为您选择的是 <li>
和 <a>
tag 是一个子标签,所以当你调用 .text(...)
时那<a>
标签被覆盖。
$(function() {
$(document).on('click', '#translate', function(e) {
var txt,
araEnglish = new Array( 'one', 'two', 'three' ),
araFrench = new Array( 'un', 'deux', 'trois' );
if ($(this).text() == 'To French') {
$(this).text('To Anglais');
$('#lstCount li').each(function(i) {
txt = araFrench[i];
if ($(this).children().length) $(this).find('*:last-child').text(txt);
else $(this).text(txt);
});
}
else {
$(this).text('To French');
$('#lstCount li').each(function(i) {
txt = araEnglish[i];
if ($(this).children().length) $(this).find('*:last-child').text(txt);
else $(this).text(txt);
});
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="lstCount">
<li>one</li>
<li><a href="*">two</a></li>
<li>three</li>
</ul>
<br/>
<button id="translate">To French</button>
关于javascript - 为什么当文本更改时,li 元素中的链接( anchor 元素)会被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34885948/