[英]Equivalent of attaching a listener to buttons on document ready in jQuery instead of vanilla JavaScript?
How do I convert this JavaScript code to jQuery code?如何将此 JavaScript 代码转换为 jQuery 代码?
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
}
Running something when the document is ready is handled by the $( document ).ready() method.在文档准备好时运行一些东西由$( document ).ready()方法处理。
getElementByClassName
can be replaced by a Class Selector (".class") getElementByClassName
可以替换为Class Selector (.class)
Your for
loop can be removed because with jQuery methods all are called on each returned element.您
for
循环可以被删除,因为 jQuery 方法都会在每个返回的元素上调用。
addEventListener
can be replaced by .click() . addEventListener
可以替换为.click() 。
Then your code is just three lines long:那么你的代码只有三行:
$(function(){
$('.btn-danger').click(removeCartItem)
})
jQuery is a library of Javascript, and therefore nothing needs to be converted. jQuery 是 Javascript 的库,因此无需转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.