如何使用jQuery获取<span>的值?


Answers:


299

我认为这应该是一个简单的例子:

$('#item1 span').text();

要么

$('#item1 span').html();

1
在哪里可以找到那些jQuery函数?
Felipe Barreiros

24
我认为在显示这两个功能时很重要,我们不要通过建议新编码者做相同的事情,不这样做而使它们混淆(尽管在本例中看起来会如此)。重要的是要注意,.text()它将对找到的所有字符进行html编码,而不.html()会对任何字符进行编码。
VoidKing

可以通过同一类的多个跨度完成此操作吗?
Matthew Woodard 2014年

我偶然发现了试图找出tspan与IE一起使用的方法。我发现您需要对tspan使用.text()而不是.html()。不确定为什么,可能不是每个人都这样,但是当我使用.text()时,它已在IE中修复。
Kalel Wade 2014年

@MatthewWoodard $('.class').each(function() { $(this).html() });; 因为$('.class').html()它将返回第一个元素的.html()值
tomsihap


7

假设您打算让它读取id =“ item1”,则需要

$('#item1 span').text()


5

由于您没有为“ item”值提供属性,因此我假设正在使用一个类:

<div class='item1'>
  <span>This is my name</span>
</div>

alert($(".item span").text());

确保您等待DOM加载以使用您的代码,在jQuery中,您ready()为此使用了函数:

<html>
 <head>
  <title>jQuery test</title>
  <!-- script that inserts jquery goes here -->
  <script type='text/javascript'>
    $(document).ready(function() { alert($(".item span").text()); });
  </script>
</head>
<body>
 <div class='item1'>
   <span>This is my name</span>
 </div>
</body>


1
您已经改变了问题!您的问题是正确的答案,他指定的ID不是类名
Lewis

好吧,如果您看到他名字下的第一条评论,您会发现他根本没有写任何属性,它是<div'item1'>,我想这显然是错误的。
Francisco Aquino

2

在javascript中,您不使用document.getElementById('item1').innertext吗?





0

非常重要有关.text()和.html()之间区别的其他信息:

如果您选择选择一个以上的项目,如您有两个跨度像现在这样 <span class="foo">bar1</span> <span class="foo">bar2</span>

然后

$('.foo').text();附上这两个文本,然后给你;而

$('.foo').html(); 仅给您其中之一。


0

您可以在HTML中直接在span中使用id。

<span id="span_id">Client</span>

然后你的jQuery代码将是

$("#span_id").text();

有人帮助我检查错误,发现他使用val()而不是text(),不可能在span中使用val()函数。所以

$("#span_id").val();

将返回null。


-2
<script>
    $(document).ready(function () {

            $.each($(".classBalence").find("span"), function () {
            if ($(this).text() >1) {
                $(this).css("color", "green")

            }
            if ($(this).text() < 1) {
                $(this).css("color", "red")
                $(this).css("font-weight", "bold")
            }
        });

    });
    </script>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.