单击香草JS版本的jQuery文档是否可获得链接? [英] Vanilla JS version of jQuery document on click for links?

查看:63
本文介绍了单击香草JS版本的jQuery文档是否可获得链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有纯JS版本?

$(document).on('click', 'a[href]', function(event) {
  event.preventDefault();
  here.change(this);
});

我要寻找的特定功能是为以后通过JS创建的任何链接添加事件监听器(例如AJAX。)

The specific feature I'm looking for is adding event listeners for any link that's created later via JS (AJAX for example).

推荐答案

现代浏览器支持匹配项

document.addEventListener('click', function(event) {
  if (event.target.matches('a[href], a[href] *')) {
    event.preventDefault();
    console.log('works fine')
  }
}, false);

document.body.innerHTML = '<a href="#"><span>Click Me!</span></a><br /><div>not me!</div>';

您可以通过简单的功能使此操作更加方便

You could make this more convenient with a simple function

function addEvent(parent, evt, selector, handler) {
    parent.addEventListener(evt, function(event) {
    if (event.target.matches(selector + ', ' + selector + ' *')) {
        handler.apply(event.target.closest(selector), arguments);
    }
  }, false);    
}

请注意, closest()仅在最新的浏览器中受支持, MDN

Note that closest() is only supported in the latest browsers, there's a polyfill on MDN

这会复制更多的jQuery行为,并且更易于使用,它还会设置 this 正确

This replicates the jQuery behaviour a lot more, and is easier to use, it also sets the value of this correctly

function addEvent(parent, evt, selector, handler) {
  parent.addEventListener(evt, function(event) {
    if (event.target.matches(selector + ', ' + selector + ' *')) {
      handler.apply(event.target.closest(selector), arguments);
    }
  }, false);
}

/* To be used as */

addEvent(document, 'click', 'a[href]', function(e) {
  console.log(this)
});

/* Add a dynamic element */

document.body.innerHTML = '<a href="#"><span>Click Me!</span></a><br /><div>not me!</div>';

这篇关于单击香草JS版本的jQuery文档是否可获得链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆