jQuery嵌套跨度文本值 [英] jQuery nested span text value

查看:78
本文介绍了jQuery嵌套跨度文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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>

我的页面上有上面的div和span.在下面的代码中,我能够获取p0的ID(警报(pID).但是,我真的想在p0的范围内获取文本.

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);
});

我应该注意,在加载表单时,我正在生成div和跨度(将它们写在jQuery中).所以这就是为什么我有.live的原因.我是在divBase0中找到嵌套跨度的最佳方法吗?其次,如何获取跨度为p0的文本?

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 .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?

谢谢!

推荐答案

只需使用 .text() 像这样获取文本内容:

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);
});

这是最好的方法吗?如果您需要ID,那么请确保(如果不需要),请使用类,如下所示:

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>

并在函数中使用类:

$("div.divBase").live("click", function () {
    alert($(this).find("span.p").text());
});

更好的一步是将处理程序附加到所有这些.divBase元素的父元素中,并使用 ,就像这样:

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.

这篇关于jQuery嵌套跨度文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆