[英]How can I properly convert the following Jquery to pure Javascript?
How can I convert the Jquery below to pure JavaScript?如何将下面的 Jquery 转换为纯 JavaScript?
var $buttons = jQuery("#thePaginator li a");
for (var index = 0; index < $buttons.length; index++) {
var $button = $buttons.eq(index);
$button.click(function() {
var newPage = $(this).data("page");
jQuery("#attribute-myAttribute").val(newPage);
jQuery("#update").click();
});
}
I wouldn't normally ask a question like this, but the conversion has been difficult, especially with the event listener.我通常不会问这样的问题,但是转换很困难,尤其是对于事件侦听器。 Here is what I have so far:
这是我到目前为止所拥有的:
runPaginate();
function runPaginate(){
var buttonArray = document.getElementById("paginator_TCC").querySelectorAll('li');
for(i=0;i<(buttonArray.length);i++){
buttonArray[i].addEventListener('click', runUpdate);
}
}
function runUpdate(){
console.log("runUpdate started")
// will need to add code in here for update
}
update (in Jquery) is a method that is called to update attributes on the page. update(在 Jquery 中)是一种被调用以更新页面属性的方法。 Consider the runUpdate function to suffice for that method call.
考虑 runUpdate 函数足以调用该方法。
I believe that I'm having so much trouble because I'm dealing with HTML Collection, so when I get the li elements (which are actually buttons) I can't seem to add an event listener to them.我相信我遇到了很多麻烦,因为我正在处理 HTML 集合,所以当我获得 li 元素(实际上是按钮)时,我似乎无法向它们添加事件侦听器。 Below is the inspection result from Dev Tools:
以下是 Dev Tools 的检查结果:
<div id="thePaginator" class="simple-pagination">
<ul>
<li class="disabled">
<span class="current prev">Prev</span>
</li>
<li class="active">
<span class="current">Year 1</span>
</li>
<li class="disabled">
<span class="current next">Next</span>
</li>
</ul>
</div>
Any assistance is appreciated.任何帮助表示赞赏。
I'd use a for...of
loop, and move the callback into the loop.我会使用
for...of
循环,并将回调移动到循环中。 That way you can access the iterator:这样你就可以访问迭代器:
for(const button of buttonArray){
button.addEventListener('click', function runUpdate() {
const { data } = button.dataset;
//...
});
}
This is the JS equivalent of your jQuery (this just replaces the jQuery method calls with their equivalent JS method calls)这是与 jQuery 等效的 JS(这只是用等效的 JS 方法调用替换了 jQuery 方法调用)
var buttons = document.querySelectorAll('#thePaginator li a');
for(var index = 0; index < $buttons.length; index++) {
var button = buttons[index];
button.addEventListener("click", function(evt) {
var newPage = this.dataset.page;
document.getElementById('attribute-myAttribute').value = newPage;
document.getElementById('update').click();
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.