javascript - 为什么当文本更改时,li 元素中的链接( anchor 元素)会被删除?

标签 javascript jquery

我在使用 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/

相关文章:

javascript - 如何从 ASP.NET MVC View 包含 Add'l .js? (.aspx)

javascript - 画中画与 WebRTC 到 Wowza

javascript - VueJS 加载更多博客文章

jquery - blockUI 可滚动内容

javascript - 如何对对象数组进行字符串化?

javascript - span 不会在列表中触发 OnClick react 子组件

javascript - 手动输入日期格式

jquery - 用户滚动时更新导航栏

javascript - 如何返回 html5 音频/视频作为 Angular 过滤器内的输出

javascript - 无法修复购物车中的总计功能