我有以下列表
$(document).ready(function() {
$('li').click(function(e) {
alert($(e.target).children().remove().end().text());
alert($(e.target).siblings('span:first').text());
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>foo1</span>
<span style="visibility: hidden">bar1</span>
</li>
<li>
<span>foo2</span>
<span style="visibility: hidden">bar2</span>
</li>
<li>
<span>foo3</span>
<span style="visibility: hidden">bar3</span>
</li>
</ul>
&#13;
我想提取&#34; foo1&#34;和&#34; bar1&#34;同时具有不同的价值观。上面的功能看起来很奇怪。有人能找到更好的方法吗?
你能调整我的jQuery函数吗?
答案 0 :(得分:3)
您应该尝试以下代码:
$(document).ready(function() {
$('li').click(function() {
console.log('span #1', this.children[0].innerHTML);
console.log('span #2', this.children[1].innerHTML);
});
});
答案 1 :(得分:1)
您可以使用find('span:first').text()
获取foo
的文字:
$(document).ready(function() {
$('li').click(function(e) {
console.log($(this).find('span:first').text());
});
});
&#13;
I have the following list $(document).ready(function() { $('li').click(function(e) { alert($(e.currentTarget).text()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>foo1</span>
<span style="visibility: hidden">bar1</span>
</li>
<li>
<span>foo2</span>
<span style="visibility: hidden">bar2</span>
</li>
<li>
<span>foo3</span>
<span style="visibility: hidden">bar3</span>
</li>
</ul>
Expand snippet I would like to get only the "foo".text() of each list element clicked. With my actual approach I also receice the "bar".text() unfortunately. Could you adjust my jQuery function please? javascript jquery target shareeditcloseflag asked
6 mins ago AppRoyale 1281217
&#13;
答案 2 :(得分:0)
您需要找到()跨度,然后执行text()或html()
$(document).ready(function() {
$('li').click(function(e) {
alert($(e.currentTarget).find('span:last-child').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>foo1</span>
<span style="visibility: hidden">bar1</span>
</li>
<li>
<span>foo2</span>
<span style="visibility: hidden">bar2</span>
</li>
<li>
<span>foo3</span>
<span style="visibility: hidden">bar3</span>
</li>
</ul>