简体   繁体   English

相当于Javascript中的jQuery代码

[英]Equivalent of jQuery code in Javascript

This is the jQuery code I have 这是我的jQuery代码

$('p').click(function(){
    alert("click successful!");
});

This is the JS code I could come up with 这是我能想到的JS代码

window.onload = function() {
    var para = document.getElementsByTagName('p');
    for(var i = 0; i < para.length; i++) {
        para[i].addEventListener('click',function(){
            alert("click successful!");
        });
    }
}

The Javascript code is too bulky, is there a way where I can select a tag by its name and write the code as - Javascript代码太笨重,有没有办法可以按名称选择标记并将代码写为 -

"If any 'p' tag is clicked, alert('click successful')" “如果点击任何'p'标签,则提醒('点击成功')”

instead of looping through all the <p></p> tags? 而不是遍历所有<p></p>标签? Any alternative way using tag name ? 使用标签名称的任何替代方式?

You can use event delegation - add a click handler to a higher level element and check event.target 您可以使用事件委派 - 向更高级别的元素添加单击处理程序并检查event.target

document.body.addEventListener("click", function(e) {
    if (e.target.tagName.toLowerCase() == "p") alert("click succeeded");
});

Demo: http://jsfiddle.net/jdkr3sch/ 演示: http//jsfiddle.net/jdkr3sch/

jQuery is "less code" because you're calling a pre-written function. jQuery是“少代码”,因为你正在调用一个预先编写的函数。 Don't want to use jQuery? 不想使用jQuery? Then write your own functions. 然后编写自己的函数。

function addEventToElements(tagname,handler) {
    var elems = document.getElementsByTagName(tagname);
    for(var i = 0, l = elems.length; i<l; i++) {
        elems[i].addEventListener('click',handler);
    }
}

Now in your actual code, you can just write: 现在在你的实际代码中,你可以写:

addEventToElements('p',function() {alert("click succeeded");});

Congratulations, you have re-invented jQuery. 恭喜,你重新发明了jQuery。

... Or not, because the reason jQuery is so popular is that it does a lot more. ...还是不行,因为jQuery的原因是如此受欢迎的是,它可以更多。 Things like normalising browser support (for those that use attachEvent or the old onEventName handlers) are half the reason jQuery exists, and you'd have to account for all of them in your own re-invention ;) 标准化浏览器支持(对于那些使用attachEvent或旧的onEventName处理程序)的onEventName是jQuery存在的原因之一,你必须在自己的重新发明中考虑所有这些;)

Here's a shorter way. 这是一个更短的方式。

document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener('click', function(evt) {
        if (evt.target.matches('p, p *')) alert('Paragraph clicked!');
    }, false);
}, false);

Notes: 笔记:

1) This has the advantage of event delegation, which is something I'd suggest looking into. 1)这具有事件委派的优点,这是我建议调查的内容。 In a nutshell, means you bind the event once, not N times, and then interrogate which element fired it when it fires, ie in the callback, not at the point of declaring the event as you are currently. 简而言之,意味着您将事件绑定一次,而不是N次,然后询问哪个元素在触发时触发它,即在回调中,而不是在您当前声明事件时。

2) For waiting to use elements, use the DOMContentLoaded event rather than window.onload - the former is (loosely) analogous to jQuery's DOM ready handler. 2)对于等待使用元素,使用DOMContentLoaded事件而不是window.onload - 前者(松散地)类似于jQuery的DOM就绪处理程序。

3) matches() is a relatively modern method and won't work in ancient browsers, or may need a vendor-prefixed version - http://caniuse.com/#feat=matchesselector 3) matches()是一种相对现代的方法,在古代浏览器中不起作用,或者可能需要以供应商为前缀的版本 - http://caniuse.com/#feat=matchesselector

for selecting: 选择:

document.querySelectorAll('p')

(also for more than one element p ). (也适用于多个元素p )。

AFAIK this is the closest thing to $('p') AFAIK这是最接近$('p')


addEventListener('click',function(){alert("click successful!")}

to add click handler to single element. 将单击处理程序添加到单个元素。


to simulate an array you can use the [].slice.call on the dom element collection (in this way you use .forEach() method) . 要模拟一个数组,你可以在dom元素集合上使用[].slice.call (这样你就可以使用.forEach()方法)。


all together: 全部一起:

[].slice.call(document.querySelectorAll('p')).
forEach(function(x){x.addEventListener('click',
    function(){alert("click successful!")
})})

https://jsfiddle.net/maio/m861hbmh/ https://jsfiddle.net/maio/m861hbmh/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM