Javascript 使用 jquery 获取 p 标签的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5287523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting value of p tag with jquery
提问by mahle
Im using jquery to try to take the value text in a p tag.
我使用 jquery 尝试获取 ap 标签中的值文本。
I set up an alert for testing to give me the value and it says "current stack is [object Object]"
我设置了一个测试警报来给我值,它说“当前堆栈是[对象对象]”
My html for this is
我的 html 是
<div id="player9">
<div class="player_stats">
<p class="player_name"></p>
<p class="player_action"></p>
<p class="player_money"></p>
</div>
</div>
My alert code is:
我的警报代码是:
alert("current stack is " + $("#player9").children(".player_stats").children("p.player_money"));
if I add .val() it comes back as undefined. These values were set upon page load by:
如果我添加 .val() 它返回未定义。这些值是在页面加载时通过以下方式设置的:
$(whichseat[seat]).children(".hand").children("p.bet").text(bet);
"whichseat[seat] and bet are based into the function. They are setting correctly.
“whichseat[seat] 和 bet 是基于功能的。它们设置正确。
If I use firebug and checkout that specific p tag it says:
如果我使用 firebug 并签出特定的 p 标签,它会说:
<p class="player_money">60000</p>
How do I correctly grab that value?
如何正确获取该值?
Any help would be greatly appreciated!
任何帮助将不胜感激!
回答by Scoobler
You could use .html()
or .text()
alert("current stack is " + $("#player9").children(".player_stats").children("p.player_money").html());
Or:
或者:
alert("current stack is " + $("#player9").children(".player_stats").children("p.player_money").text());
Obviously the text method will grab just the text, where as the html will get the markup as well. Demo Here
显然 text 方法将只获取文本,而 html 也会获取标记。演示在这里
回答by Abdel Raoof
You can use the text()
method. The val() method is used for getting input field's values. So, you will have:
您可以使用该text()
方法。val() 方法用于获取输入字段的值。因此,您将拥有:
alert("current stack is " + $("#player9").children(".player_stats").children("p.player_money").text());
回答by BoltClock
Not sure what else I'm missing, but since you're setting the inner text with .text()
, you get it using the same method.
不确定我还缺少什么,但是由于您使用 设置内部文本.text()
,因此您可以使用相同的方法获取它。
If all else fails you may have to specify to get the inner text of exactly one element:
如果所有其他方法都失败了,您可能必须指定获取恰好一个元素的内部文本:
$("#player9 > .player_stats > p.player_money:first").text()