jQuery获取span的内容 [英] JQuery get content of span
问题描述
我正在尝试单击按钮时获取跨度的内容.这是html:
I'm trying to get the content of a span when a button is clicked. This is the html:
<div class="multiple-result">
<button class="select-location" id="168">Select</button>
<span>Athens, Greece</span>
</div>
<div class="multiple-result">
<button class="select-location" id="102">Select</button>
<span>Athens, Georgia, USA</span>
</div>
我正在尝试获取它,以便在单击按钮时将获取跨度的值.这就是我正在使用的:
I'm trying to get it so that when the button is clicked it will get the value of the span. This is what I'm using:
$('button.select-location').live('click', function(event){
// set the span value
var span_val = $(this).parent("span").html();
alert('selecting...' + span_val);
});
但是警报始终显示:选择... null
But the alert is always showing: selecting... null
推荐答案
您要先获取父项,然后找到跨度:
You want to get the parent first, then find the span:
var span_val = $(this).parent().find("> span").html();
.children("span")而不是.find("> span")
.
Ever go back and look at code you wrote 2 years ago and groan, "Why did I do that?". The above code is awkward. Instead of .find("> span")
, I should have used .children("span")
.
var span_val = $(this).parent().children("span").html();
但是,您父母的孩子是什么?兄弟姐妹!因此,我应该使用.siblings("span")
代替.parent().children("span")
.
But, what is a child of your parent? A sibling! So, instead of .parent().children("span")
, I should have used .siblings("span")
.
var span_val = $(this).siblings("span").html();
但是,查看HTML,我们甚至不需要深入研究同级兄弟,我们知道这是下一个同级兄弟:
But, looking at the HTML, we don't even need to dig through the siblings, we know it's the next sibling:
var span_val = $(this).next("span").html();
或者只是:
var span_val = $(this).next().html();
至此,我们几乎没有使用jQuery.我们可以说:
By this point, we're barely using jQuery at all. We could just say:
var span_val = this.nextSibling.innerHTML;
但是,也许现在我已经将摆锤摆得太远了?
But, maybe now I've swung the pendulum too far the other way?
这篇关于jQuery获取span的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!