【问题标题】:Change the Action from Href to Onclick Dynamically将动作从 Href 动态更改为 Onclick
【发布时间】:2014-02-04 07:01:08
【问题描述】:

我有 Html 一个标签,它有一个 href 属性,这个标签没有任何类或 id,但它的父母有,但父元素的 id 永远不会相同[它是动态内容]。我想删除 href 属性并将 onclick 事件应用于它。 onclick 的值应该与 href 相同。我写了一个 jquery 代码,但它只改变了第一个。请注意,我不是动态地构造这个元素。我只能改变它的属性。

HTML

<body>
<div id="AUDITOR_ASSIGNMENTS_field__div">    
<a aria-label="Open Assignments" href="javascript:getmlov(98,22,2)">Click Me</a>
</div>    
<div id="_1__AUDITOR_ASSIGNMENTS_field__div">    
<a aria-label="Open Assignments" href="javascript:getmlov(99,21,2)">Click Me</a>
</div>
<div id="_3__AUDITOR_ASSIGNMENTS_field__div">    
<a aria-label="Open Assignments" href="javascript:getmlov(102,13,1)">Click Me</a>
</div> 
</body>

jQuery

$('#AUDITOR_ASSIGNMENTS_field__div a').each(function() {
      var href = $(this).attr('href');
      $(this).attr('onclick', href)
         .removeAttr('href');
  });

Jsfiddle http://jsfiddle.net/d2vL6/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    用途:

     $("[id$='AUDITOR_ASSIGNMENTS_field__div']").find('a').each(function() {
      var href = $(this).attr('href');
      $(this).attr('onclick', href)
         .removeAttr('href');
    });
    

    Demo

    【讨论】:

    • 尝试使用$(this).prop('onclick', href);
    • 我已经修改了代码并且工作正常,唯一的问题是我不知道如何调用存储在字符串 href 中的函数。 $("[id$='AUDITOR_ASSIGNMENTS_field__div']").find('a').each(function() { var href = $(this).attr('href'); href = href.split(": ")[1]; //$(this).attr('onclick', href +'; return false;') $(this).removeAttr('href'); $(this).click(function() { href; }); });
    【解决方案2】:

    这是另一种解决方案

      $('div a').each(function() {
         var href = $(this).attr('href');
         $(this).attr('onclick', href)
           .removeAttr('href');
      }); 
    

    【讨论】:

    • 我认为这应该可行 $(this).click(href) .removeAttr('href');
    猜你喜欢
    • 2014-11-21
    • 2015-07-16
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2011-08-12
    • 2013-02-28
    • 2023-03-22
    • 2016-11-10
    相关资源
    最近更新 更多