Javascript - 查找<a> tag, where href attribute contains a string, prevent default event and override

时间:2017-05-26 10:09:17

标签: javascript jquery html

I am having this code right now, which works just fine with links with an ID.

 var buttonclick = document.getElementById("myLink");
    buttonclick.addEventListener("click", function(event){
    event.preventDefault(); window.location = 'facebook.com'
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="google.com" id="myLink">google</a>

What I want to do is get all links without an ID, just the ones which contain the world 'google' in the href attribute, and apply the same events further in my original code.

I have tried combining with jQuery, and all I managed to do is:

$('a[href*="google"]')

I am not sure how to combine it with the code above. Thank you in advance.

2 个答案:

答案 0 :(得分:0)

您可以使用document.querySelector(selector)

执行此操作
var buttonclick = document.querySelector('a[href*="google"]');
buttonclick.addEventListener("click", function(event){
   event.preventDefault(); 
   window.location = 'facebook.com'
});

如果您想定位与选择器匹配的所有元素,那么只需使用querySelectorAll代替querySelector

document.querySelectorAll('a[href*="google"]').forEach(function(button){
  button.addEventListener("click", function(event){
    event.preventDefault(); 
    window.location = 'facebook.com'
  });
});

编辑使用函数forEach属于nodeList对象。它的灵感来自@ rory的答案。

答案 1 :(得分:0)

您可以通过在jQuery代码中使用click()处理程序来实现此目的。试试这个:

$('a[href*="google"]').click(function(e) {
  e.preventDefault(); 
  window.location.assign('http://facebook.com');
});

如果您更喜欢使用普通JS,那么您可以使用querySelectorAll(),如下所示:

[].forEach.call(document.querySelectorll('a[href*="google"]'), function(el) {
  el.addEventListener('click', function(e) {
    e.preventDefault();
    window.location.assign('http://facebook.com');
  });
});