【问题标题】:Getting the Name of href - jquery获取href的名称 - jquery
【发布时间】:2013-06-12 10:16:11
【问题描述】:

我正在做一个项目,我需要获取 href 属性的名称,以便使用 Inner.html 在特定位置显示它。我不知道如何获取 name 属性的值。。

HTML:

<p class="datarange"> 
    Select Date Range: 
    <a href="#" name="month" onclick="Lab()">Last Month </a>|
    <a href="#" name="2 weeks" onclick="Lab()"> Last 2 Weeks </a>|
    <a href="#" name="1 week" onclick="Lab()"> Last 1 Week</a>
</p>

Javascript:

function Lab()
{       
    var a = $(this).attr('href');       
    console.log(a)
    document.getElementById("lin").innerHTML="Last" +a;
}

【问题讨论】:

  • "我需要获取 href 属性的名称" href 属性的名称是href。您想获取a 元素的名称吗?仅供参考,在您的事件处理程序中,this 指的是window,而不是处理程序绑定到的 DOM 元素。
  • 感谢费利克斯的信息。已注明。

标签: javascript jquery html innerhtml


【解决方案1】:

试试:

$(document).ready(function(){
    $('a').click(function(e){
        e.preventDefault(),
        var a = this.name;
        document.getElementById("lin").innerHTML="Last" +a;
    });
});

【讨论】:

    【解决方案2】:

    你可以这样做:

    HTML:

    <a href="#" name="2 weeks" onclick="Lab(this);"> Last 2 Weeks </a>|
    <a href="#" name="1 week" onclick="Lab(this);"> Last 1 Week</a>
    
    • this 传递给Lab 函数。

    JS:

    function Lab(obj) {
        var name = obj.name
        console.log(name);
    }
    
    • 您可以在控制台中查看链接名称。

    FIDDLE DEMO

    【讨论】:

      【解决方案3】:

      试试

      $("#lin").html("Last" +$(this).attr('name'));
      

      作为一个旁注,当你有 jquery 时为什么这个document.getElementById("lin")

      使用$("#lin")

      【讨论】:

        【解决方案4】:

        您当前正在获取href 属性的值。将'href' 更改为'name'

        var a = $(this).attr('name');
        

        【讨论】:

          【解决方案5】:

          不显眼的事件处理程序优于内联,您可以使用$(this).attr('name') 获取名称。

          $(document).ready(function(){
              $('a').click(function(){
                  console.log( $(this).attr('name') );
                  return false;
              });
          });
          

          【讨论】:

            猜你喜欢
            • 2015-05-12
            • 2016-02-01
            • 2014-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-28
            • 2013-09-12
            • 2015-10-22
            相关资源
            最近更新 更多