2014-10-19 121 views
-1

如何为页面中的每个'a'标记执行此操作。我的目标是使用Google的搜索结果来访问没有谷歌重定向的结果(在href属性中使用),因为实际链接存储在data-href属性中。因此,使用Tampermonkey与下面的脚本没有工作,我don'k知道为什么:使用Javascript替换使用data-href属性的href属性

$('body').append('<input type="button" value="Fix Href Attributes" id="GG">'); 
$("#GG").css("position", "fixed").css("top", 18).css("left", 770); 

$('a').each(function(){ 
       var $currentA = $(this); 
       var dataHref = $currentA.attr('data-href'); 
       $currentA.attr('href',dataHref); 
      }); 

我怎样才能做到这一点?

+0

灿你会在操作前后显示你的元素的一个例子,以显示你想要的结果? – 2014-10-19 11:29:27

+0

让Google知道您点击的搜索结果是*有用*。此反馈用于不断改进每个人的搜索结果。使用类似上述的脚本意味着您停止对该反馈作出贡献,并且只从其他人提供的反馈中受益,而不会互动。 – 2014-10-19 11:34:07

+0

这里有[undirect](https://github.com/xwipeoutx/undirect),不需要重新发明轮子。 – georg 2014-10-19 11:35:50

回答

0

您的代码更新元素是正确的,你只是太快发射它。火了响应按钮被点击:

$('body').append('<input type="button" value="Fix Href Attributes" id="GG">'); 
$("#GG").css("position", "fixed").css("top", 18).css("left", 770).on("click", function() { 
    $('a').each(function() { 
     var $currentA = $(this); 
     var dataHref = $currentA.attr('data-href'); 
     $currentA.attr('href', dataHref); 
    }); 
}); 

还有就是,当然没有理由你需要给它一个ID并将其附加后,看看它:

$('<input type="button" value="Fix Href Attributes">') 
    .css({ 
     position: "fixed", 
     top: 18, 
     left: 770 
    }) 
    .on("click", function() { 
     $('a').each(function() { 
      var $currentA = $(this); 
      var dataHref = $currentA.attr('data-href'); 
      $currentA.attr('href', dataHref); 
     }); 
    }) 
    .appendTo(document.body); 
+0

Hi T.J. Crowder, 我使用按钮触发脚本,但我不工作。这是这个问题。你可以用篡改密钥试试它,并尝试与我诊断问题? 以下是篡改密钥的附加信息: '// @match *://www.google.com/search?*' '// @require http://code.jquery.com/jquery-latest.js ' – Synchro 2014-10-20 13:13:23