gpt4 book ai didi

javascript - 仅当 Javascript 中存在类时才允许监听器事件运行

转载 作者:行者123 更新时间:2023-12-02 16:50:08 25 4
gpt4 key购买 nike

我构建了一个进度栏 Javascript 对象,当用户单击绑定(bind)了“click”事件监听器的左侧或右侧按钮时,该对象会更新进度栏。我只希望这些按钮在附加了某个类时触发单击事件,在本例中是一个名为“progress-bar-ok”的类。到目前为止,我似乎想不出在我的代码中执行此操作的方法。这是我的代码:

Javascript 对象:

//Progress Bar
var ProgressBar = function(element, startVal, endVal, step, addLefts, addRights) {
this.element = element;
this.endVal = endVal;
this.currentVal = startVal;
this.step = step;
this.addLefts = addLefts;
this.addRights = addRights;
var self = this;
}

ProgressBar.prototype.initializeProgressBar = function() {
jQuery(this.element).progressbar({
value : this.currentVal,
max : this.endVal,
step : this.step
});
for(var i = 0; i < this.addLefts.length; i++) {
this.addLefts[i].addEventListener("click", this.removeAmount.bind(this), false);
}
for(var i = 0; i < this.addRights.length; i++) {
this.addRights[i].addEventListener("click", this.addAmount.bind(this), false);
}
}

ProgressBar.prototype.addAmount = function() {
if(this.currentVal < this.endVal) {
this.currentVal += this.step;
this.update();
}
}

ProgressBar.prototype.removeAmount = function() {
console.log(self);
if(this.currentVal > 0) {
this.currentVal -= this.step;
this.update();
}

}

ProgressBar.prototype.update = function() {
jQuery(this.element).progressbar({
value : this.currentVal
});
}

Javascript 客户端代码

//Progress Bar
var addLefts = document.getElementsByClassName("btn-lft");
var addRights = document.getElementsByClassName("btn-right");
var progressBar = new ProgressBar("#progress-bar", 0, jQuery(".signup-part").length, 1, addLefts, addRights);
progressBar.initializeProgressBar();

正如您所看到的,附加了点击监听器的“addLefts”和“addRights”,我只想在“progress-bar-ok”类存在时触发“addAmount”和“removeAmount”函数。有没有办法将其合并到我的代码中?谢谢

最佳答案

你可以像这样检查 DOM 中是否存在带有类的元素

if ($('.progress-bar-ok').length) {
your code
}

关于javascript - 仅当 Javascript 中存在类时才允许监听器事件运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26739424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com