jQuery替换所有href ="" with onclick =" window.location ="

时间:2012-02-23 03:57:45

标签: javascript jquery

所以我对你来说很酷。

我需要扫描我的html文档,因为它正在渲染并替换每个

href=""

onclick="window.location=''"

更重要的是,我需要携带从href到window.location的链接。

例如,如果我有:

href="http://www.google.com.au"

它会变成:

onclick="window.location='http://www.google.com.au'"

我需要它在文档中的每个href

上执行此操作

我不知道,但它需要在jQuery / javascript:D

谢谢你们。

3 个答案:

答案 0 :(得分:8)

你可以试试这个:

$('a').each(function() {
  var href = $(this).attr('href');
  $(this).attr('onclick', "window.location='" + href + "'")
         .removeAttr('href');
});

你想用这个来实现什么?有可能有一种更优雅的方式来实现你所追求的目标。

例如,在JS中自己处理事件可能更好。将第三行替换为:

$(this).click(function() { window.location = href; })

这可能会变得非常昂贵,所以你可能想要考虑jQuery的delegate事件:http://api.jquery.com/delegate/

答案 1 :(得分:3)

这应该达到你想要的......

$('a[href]').click(function(event) {
   event.preventDefault();
   window.location = this.href;
});

我假设您想要阻止链接的默认行为。

对于所有可能的链接,您可以使用document.links

对于所有链接和将来的链接,请使用事件委派。

$('body').on('click', 'a[href]', function() {
       window.location = this.href;
});

答案 2 :(得分:2)

一些非jQuery变体:

保持href:

var i = document.links.length;
while (i--) 
  document.links[i].onclick = function(){window.location = this.href;};

保持href并且如果onclick被调用则不要跟随它(即使它去了同一个地方):

var i = document.links.length;
while (i--) 
  document.links[i].onclick = function() {
    window.location = this.href;
    return false;
  };

删除href:

var i = document.links.length,
    link;
while (i--) {
  link = document.links[i]; 
  link.onclick = (function(href) {
    return function() {
        window.location = href;
    }(link.href));
  link.href = '';
}
link = null;

当然,我不明白为什么你要用一个不可靠,容易破解的解决方案替换一个强大的,无处不在的解决方案。