jQuery替换所有href=""其中onclick=“;window.location=“;

jQuery replace all href="" with onclick="window.location="

本文关键字:quot 替换 window location onclick 其中 jQuery href      更新时间:2023-09-26

所以我给你准备了一个很酷的。

我需要扫描我的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中

谢谢大家。

你可以试试这个:

$('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/

这应该可以实现您想要的。。。

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

我想你是想防止链接的默认行为。

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

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

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

一些非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;

当然,我不明白你为什么要用一个不可靠、容易坏掉的解决方案来取代一个健壮、随处可用的解决方案。