Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery将onClick事件附加到锚标记?_Javascript_Jquery - Fatal编程技术网

Javascript 使用jquery将onClick事件附加到锚标记?

Javascript 使用jquery将onClick事件附加到锚标记?,javascript,jquery,Javascript,Jquery,我正在尝试将onClick事件添加到锚标记 以前我有 但是我试图避免内联onClick事件,因为它会干扰另一个脚本 因此,我使用jQuery尝试以下代码 <script> $(document).ready(function() { $('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null; pageTracker._link(this.href);

我正在尝试将onClick事件添加到锚标记

以前我有

但是我试图避免内联onClick事件,因为它会干扰另一个脚本

因此,我使用jQuery尝试以下代码

<script>
    $(document).ready(function() {
      $('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
        pageTracker._link(this.href); 
        return false;
      });
    });
</script>

$(文档).ready(函数(){
$('a#tracked').attr('onClick')。单击(函数(){window.onbeforeunload=null;
pageTracker.\u链接(this.href);
返回false;
});
});
像这样的html

所以我的问题是,这是否可行,如果不行,最好的解决方案是什么?

正确的方法是(对于jQuery)

这将在任何具有跟踪id的元素上添加一个“onclick”事件。在那里,您可以做任何您想做的事情。单击事件发生后,第一行将单击元素的href属性传递给pageTracker

至于你原来的问题,它不起作用,它会引起未定义的错误。attr的工作原理有点不同。看见您使用它的方式将返回属性的值,我认为在这种情况下,它不是可链接的。如果您想保持原来的状态,应该如下所示:

$('#tracked').click(function() {
    $(this).attr('onclick', 'pageTracker._link(this.href); return false;');

    return false;
});
你也可以试试

var element1= document.getElementById("elementId");
然后

element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");   

//在这里,我试图设置element1的onchange事件(一个下拉列表)以重定向到函数()

我昨天花了一些时间。事实证明,我需要在$(window.ready)而不是$(document.ready)上包含jQuery


有一个Noob的后续问题我应该把它放在哪里?在'
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");   
$( window ).ready(function() {
  $('#containerDiv a').click(function() {
    dataLayer.push({
      'event': 'trackEvent',
      'gtmCategory': 'importantLinkSimilarProperties',
      'gtmAction': 'Click',
      'gtmLabel': $(this).attr('href')
    });
  });
});