这是我现在所拥有的,但它不起作用:
<script>
jQuery(function($){
$(document).ready(function(){
$("a").attr('onclick', 'return goog_report_conversion(' + this.attr('href') + ')');
});
});
</script>
我是否错误地使用了“this”关键字?
最佳答案
如果您不打算在元素中内联分配onclick
,我认为您没有理由不使用标准事件处理程序。您可以阅读更多有关好处的信息here .
我建议这样做:
$("a").click(function() {
var href = $(this).attr("href");
return goog_report_conversion(href);
});
此外,您的前两行代码执行相同的任务,因此您不需要同时执行这两行代码。 (More info here)
jQuery(function($){ ... });
// OR
$(document).ready(function() { ... });
<小时/>
如果您想知道为什么您的不起作用:
attr()
没有自己的 this
参数。
(向上追踪,您使用它的上下文实际上会引用 document
,因为范围由 $(document).ready( 定义) ...)
)
如果您要这样做,您可能需要修改您的 goog_report_conversion()
函数以接受单击元素的参数,而不是href
。您的 this
将包含在字符串中,而不是连接起来。使用传递的元素,您可以像我们在上面的示例中所做的那样获取 href
。
function goog_report_conversion(clicked_element) {
var href = $(clicked_element).attr("href");
//do something with href
});
$("a").attr("onclick", "return goog_report_conversion(this);");
话虽这么说,请不要这样做。
关于javascript - 我可以使用 jQuery 根据另一个属性的值设置一个属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897121/