单击香草JS版本的jQuery文档是否可获得链接?

编程入门 行业动态 更新时间:2024-10-23 08:36:50
本文介绍了单击香草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文档是否可获得链接?

本文发布于:2023-11-30 03:25:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:香草   可获得   单击   版本   文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!