代码之家  ›  专栏  ›  技术社区  ›  Dean J

使用JQuery查找标记的值/文本

  •  1
  • Dean J  · 技术社区  · 15 年前

    这里有些不太对劲。

    $(document).ready(function() 
            { 
                $("a#edit").click(function() {
                    $("div#search").addClass("hidden");
                    $("div#edit").removeClass("hidden");
                alert((this).val());
                return false;
                }); 
            } 
    ); 
    

    后来:

    <a href="#" id="edit">10.1001</a>
    

    我想从中得到值“10.1001”。 alert((this).val()); 似乎不起作用,也不起作用 alert((this).text()); . 有人能很快指出我这里遗漏了什么吗?谢谢!

    3 回复  |  直到 15 年前
        1
  •  4
  •   Nick Craver    15 年前

    而不是 (this).val() 你想要什么 $(this).text()

    .val() 用于输入类型元素, .text() 用于获取标记中的文本:)

    您的代码总体上应该是这样的,注意addd $ (this) :

    $(function() {
      $("a#edit").click(function() {
        $("div#search").addClass("hidden");
        $("div#edit").removeClass("hidden");
        alert($(this).val());
        return false;
      });
    }); 
    
        2
  •  2
  •   James    15 年前

    你好像忘了关键的问题 $ 符号(的别名) jQuery ),后跟括号时( (...) ),调用jQuery构造函数并提供其所有方法。

    alert( $(this).text() );
    

    关键字 this 实际上提供了对被单击的DOM元素的引用,以及 val text 未在上实现 DOMElement . 通过在jQuery对象中包装DOM元素,可以访问这些方法。

        3
  •  1
  •   David Thomas    15 年前

    尝试:

    $(document).ready(function() 
            { 
                $("a#edit").click(function() {
                    $("div#search").addClass("hidden");
                    $("div#edit").removeClass("hidden");
                alert($(this).text()); // $(this).text() should return the text contained within the relevant tag.
                return false;
                }); 
            } 
    );