jQuery nested span text value
<div id="divBase0" class="divBase">
<span id="p0" class="displayText">text line 1</span>
<span id="l0" class="displayText">text line 2</span>
<span id="f0" class="displayText">text line 3</span>
<span id="d0" class="displayText">text line 4</span>
<span id="t0" class="displayText">text line 5</span>
</div>
I have the above div and spans in my page. In the following code I am able to get the id of p0 (alert(pID). However I really want to get the text inside the span of p0.
$("div[id^='divBase']").live("click", function () {
var pID = $(this).find("span[id^='p']").attr("id");
alert(pID);
});
I should note that I'm generating the divs and the spans (writing them out in jQuery) when the form loads. So that is why I have the 开发者_JAVA技巧.live. Am I doing it the best way to find the nested span(s) in the divBase0? And secondly how can I get the text in span p0?
Thanks!
Just use .text()
to get the text inside, like this:
$("div.divBase").live("click", function () {
var pText = $(this).find("span[id^='p']").text();
alert(pText);
});
Is this the best way? If you need the IDs then sure, if not then just use classes, like this:
<div class="divBase">
<span class="p displayText">text line 1</span>
<span class="l displayText">text line 2</span>
<span class="f displayText">text line 3</span>
<span class="d displayText">text line 4</span>
<span class="t displayText">text line 5</span>
</div>
And use classes in your functions:
$("div.divBase").live("click", function () {
alert($(this).find("span.p").text());
});
One step better would be attaching the handler to the parent element all these .divBase
elements are in with .delegate()
, like this:
$("#divContainer").delegate("div.divBase", "click", function () {
alert($(this).find("span.p").text());
});
This eliminates the initial selector performance cost as well as being cheaper or future clicks.
精彩评论