繁体   English   中英

jQuery的跨度值是空的,HTML不是吗?

[英]jquery getting value of span is empty, html is not?

我有4个div,其中有一个随机数

调用$("#result1 span").text() ,输出为空白。 但是,在调用$("#result1 span").html() ,输出将给出值。

没有html,如何获取值?

输出是这样的:

<style type="text/css">
        #number {position:relative; top:-225px;left:584px;width:230px;height:10px;}
        #number span {padding:14px; margin:2px; color:orange; font-size:30px;}
        #number input:hover{opacity:0.9; filter:alpha(opacity=90);}
        #number input{opacity:1.0; filter:alpha(opacity=100);}
        #generate {position:relative; top:35px; left:-1px; width:95px; height:25px;}
        #reset {position:relative; top:35px; left:5px; width:95px; height:25px;}
    </style>1

我需要的值就在结束</style>标记"1"

完整的HTML:

<div id="number">
<span id="result1"></span>
<span id="result2"></span>
<span id="result3"></span>
<span id="result4"></span>
<button id="generate">Generate</button>
<button id="reset">Restart</button>
</div>

使用Javascript:

$('#result1').html((Math.random() * 10) >> 0);
$('#result2').html((Math.random() * 10) >> 0);
$('#result3').html((Math.random() * 10) >> 0);
$('#result4').html((Math.random() * 10) >> 0);

尝试以下操作:(这应该一一返回所有4个跨度内的文本)

$("#result1 span").each (function () {
    console.log($(this).text());
});

至少一件事-您的选择器是错误的。 $(“#result1 span”)。text()不会给您任何东西,因为result1 内部没有跨度,result1 一个跨度。 将选择器更改为$(“#result1”)并查看得到的结果。

只需更改选择器就对我有效:

http://jsfiddle.net/ccross59/TnbCc/1/

如果可以将“需要此文本”放在带有ID的范围内,则要容易得多,然后只需获取该ID的.text()。 如果您无法更改标记,则可以获取span的.html()并在“”之后的内容进行字符串匹配,但这非常脆弱。

我想我看到你的问题了。 $(“#result1 span”)。text()相当于$('#result1')。find('span')将查找嵌套在“#result1”中的第一个span的文本

它看起来像“#result1”没有任何嵌套的跨度,并且您实际上希望跨度的文本值为“#result1”。

如果我是正确的$('#result1')。text()是您要寻找的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM