Javascript-Find<;a>;标记,其中href属性包含字符串,防止默认事件并覆盖

Javascript-Find<;a>;标记,其中href属性包含字符串,防止默认事件并覆盖,javascript,jquery,html,Javascript,Jquery,Html,我现在有这个代码,它可以很好地处理带有ID的链接 var buttonclick=document.getElementById(“myLink”); 按钮单击addEventListener(“单击”),函数(事件){ event.preventDefault();window.location='facebook.com' }); 你可以用 如果要将所有与选择器匹配的元素作为目标,则只需使用而不是querySelector document.querySelectorAll('a[hre

我现在有这个代码,它可以很好地处理带有ID的链接

var buttonclick=document.getElementById(“myLink”);
按钮单击addEventListener(“单击”),函数(事件){
event.preventDefault();window.location='facebook.com'
});

你可以用

如果要将所有与选择器匹配的元素作为目标,则只需使用而不是
querySelector

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

编辑以使用函数
forEach
属于节点列表对象。它的灵感来自@rory的回答。

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

$('a[href*="google"]').click(function(e) {
  e.preventDefault(); 
  window.location.assign('http://facebook.com');
});
如果您喜欢使用纯JS,那么可以使用
querySelectorAll()
,如下所示:

[].forEach.call(document.queryselectorl('a[href*=“google”]”),函数(el){
el.addEventListener('click',函数(e){
e、 预防默认值();
window.location.assign('http://facebook.com');
});
});

$('a[href*=“google”]”)。在(“单击”,functionName)
上,您是否应该定义一个函数,然后将其分配给所有单击事件?这对一个链接有效,已经很好了。谢谢你。@Rorymcrossan我不知道
nodeList
有一个名为
forEach
的函数。它有,但它在IE中没有支持。我将它更新为更可靠的跨浏览器版本
$('a[href*="google"]').click(function(e) {
  e.preventDefault(); 
  window.location.assign('http://facebook.com');
});