【问题标题】:jQuery: How to get the value of an html attribute?jQuery:如何获取 html 属性的值?
【发布时间】:2009-12-04 05:30:06
【问题描述】:

我有一个 html 锚元素:

<a title="Some stuff here">Link Text</a>

...我想获取标题的内容,以便将其用于其他用途:

$('a').click(function() {
    var title = $(this).getTheTitleAttribute();
    alert(title);
});

我该怎么做?

【问题讨论】:

    标签: jquery


    【解决方案1】:
    $('a').click(function() {
        var title = $(this).attr('title');
        alert(title);
    });
    

    【讨论】:

    • @KolobCanyon prop 用于属性(如disabledreadonly 等)attr 用于属性(attribute=value)。属性不包含值,它们单独存在时是活动的,即&lt;input disabled/&gt; 属性包含值&lt;input attribute=value/&gt;
    【解决方案2】:
    $('a').click(function() {
        var title = $(this).attr('title');
        alert(title);
    });
    

    【讨论】:

      【解决方案3】:
      $(this).attr("title")
      

      【讨论】:

        【解决方案4】:

        你可以简单地在函数内部使用this.title

        $('a').click(function() {
            var myTitle = $(this).attr ( "title" ); // from jQuery object
            //var myTitle = this.title; //javascript object
            alert(myTitle);
        });
        

        注意

        使用另一个变量名而不是“警报”。 Alert 是一个 javascript 函数,不要将其用作变量名

        【讨论】:

          【解决方案5】:

          您可以创建函数并从 onclick 事件中传递此函数

          <a onclick="getTitle(this);" title="Some stuff here">Link Text</a>
          
          <script type="text/javascript">
          
          function getTitle(el)
          {
               title = $(el).attr('title');
               alert(title);
          }
          
          </script>
          

          【讨论】:

            【解决方案6】:

            如果你想捕获对文档的每次点击并获取属性值,你也可以试试这个:

            $(document).click(function(event){
                var value = $(event.target).attr('id');
                alert(value);
            });
            

            【讨论】:

              猜你喜欢
              • 2013-06-19
              • 2023-03-22
              • 2021-03-14
              • 2016-07-31
              • 1970-01-01
              • 2023-03-21
              • 1970-01-01
              • 1970-01-01
              • 2013-05-24
              相关资源
              最近更新 更多