[英]jQuery/javascript: how to distinguish between different table rows of the same percentage selector?
通过使用javascript代码将其插入DOM中,在html结构的表的表行/单元格td中创建此片段N次。
<div class="noselect">
<div class="class_innerPercentage clearfix">
<label for="up"></label>
<input id="input" type="number" min="0" max="100" step="5"
value="100" class="noselect" readonly="readonly">
</input>
<label for="down"></label>
</div>
</div>
这种插入是通过类似以下方式完成的:
$("#id_createNewRow").click(function () {
$('#start_bottom_line').before('<tr><td>....
最终我得到类似:
除了在DOM中插入外,还为每个新表行安装了一个事件侦听器:
$("label[for=down],label[for=up]").on("click", function (event) {
$("#input").val(function (_, n) {
return event.target.htmlFor === "up"
? +n < +this.max ? +n + 5 : n
: +n > +this.min ? +n - 5 : n;
}).trigger("arrow")
});
单击引用箭头的上/下按钮时,仅应为表中实际单击的行增加/减少。
目前仅第一行增加/减少。
我该如何正确地增加/减少当前单击的行?
您有几个HTML问题:
首先,请注意HTML <input>
元素没有结束标记。 删除</input>
。
同样,许多浏览器不支持type=number
,并且默认情况下将返回没有任何箭头可单击的文本框。 请参阅此处以获取浏览器支持
另外(也是最重要的一点),如果您重复创建相同的HTML代码段,那么最后您将得到包含id
为input
的元素的每一行,因此,当事件处理程序继续寻找它时,它将始终停止在它找到的第一个。
您需要确保插入的每个元素都具有唯一的id
。
完成此操作后,可以更改事件处理程序以访问当前行:
$(".class_innerPercentage").on("click", "label[for=down],label[for=up]" , function (event) {
var theInput = this.parentNode.querySelector("input");
$(theInput).val(function (_, n) {
return event.target.htmlFor === "up"
? +n < +this.max ? +n + 5 : n
: +n > +this.min ? +n - 5 : n;
}).trigger("arrow")
});
使用数据属性而不使用id对其进行简化。 输入是标签的同级。
$("label[data-dir]").on("click", function(e) { //select the labels and bind click var label = $(this), //label dir = label.data("dir"), //get step direction to increase or decrease input = label.siblings("input"), //find the input that is a sibling of the label step = Number(input.attr("step")), //Get the step, no need to hard code it in the JavaScript min = Number(input.attr("min")), max = Number(input.attr("max")), updatedVal = Number(input.val()) + (dir*step); //change the value with the step size if (updatedVal>max) updatedVal = max; else if (updatedVal<min) updatedVal = min; input.val( updatedVal ); e.preventDefault(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="noselect"> <div class="class_innerPercentage clearfix"> <label for="input1" data-dir="-1">-</label> <input id="input1" type="number" min="0" max="100" step="5" value="100" class="noselect" readonly="readonly"> <label for="input1" data-dir="1">+</label> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.