简体   繁体   English

$(this).attr(“href”)不起作用

[英]$(this).attr(“href”) not working

For some reason, this line of code is returning undefined for $(this).attr("href") 由于某种原因,这行代码返回undefined为$(this).attr("href")

$("a").attr("href", "javascript:page('" + $(this).attr("href") + "')");

How can I get that value? 我怎样才能获得这个价值?

$("a").click(function(e){
    e.preventDefault();
    page(this.href);
});

Try: 尝试:

$("a").attr("href", function (index, oldHref) {
    return "javascript:page('" + oldHref + "')");
});

Check out the documentation for attr for information about the overload that takes a function reference. 查看attr的文档,了解有关带有函数引用的重载的信息。

Although as @Pointy points, out, you should consider writing an event handler instead of using javascript: inside your markup. 虽然@Pointy指出,你应该考虑编写一个事件处理程序而不是使用javascript:在你的标记中。

This is an alternative approach that doesn't require Javascript on your href attribute 这是一种替代方法,不需要在您的href属性上使用Javascript

$('a').click( function(e) {
    e.preventDefault();
    page(this.href);
} )

You don't need inline javascript, why not do like below: 你不需要内联javascript,为什么不这样做:

$("a").click(function(){
    page(this.href);
    return false;
});

If you want to do that (update all href attribute of the links on the page) you could do 如果你想这样做(更新页面上链接的所有href属性),你可以这样做

$("a").each(function() {
   $(this).attr("href", "javascript:page('" + $(this).attr("href") + "')");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM