2014-10-19 119 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