[英]Traversing with jQuery: cycle over children
大家好,我有一个类似html的结构:
<tr>
<td>
<div class="sigle-sz">
<span class="label-sz">36</span> <input class="" type="tel" value="" name="">
<div class="available yes">
<i aria-hidden="true" class="availablespot"></i>
</div>
</div> <!-- /sigle-sz -->
</td>
<td>
<div class="sigle-sz">
<span class="label-sz">38</span> <input class="" type="tel" value="" name="">
<div class="available yes">
<i aria-hidden="true" class="availablespot"></i>
</div>
</div> <!-- /sigle-sz -->
</td>
<td>
<div class="sigle-sz">
<span class="label-sz">40</span> <input class="" type="tel" value="" name="">
<div class="available yes">
<i aria-hidden="true" class="availablespot"></i>
</div>
</div> <!-- /sigle-sz -->
</td>
</tr>
我创建了这样的jQuery函数:
<script>
function pippo() {
//code here
}
$( document ).ready(function() {
$( ".sigle-sz" ).on('change', function() {
pippo();
});
});
</script>
我将在函数“ pippo()
”中循环<tr>
标记中的<td>
元素,并将输入值保存在变量中。
如果this
是$( ".sigle-sz" )
元素,我该怎么做?
我在这里输入了我当前的代码: https : //jsfiddle.net/ydrunbzz/
您可以使用$.each()
jQuery函数 :
var values; // define global var to use everywhere
function pippo(myClass) {
$.each(("." + myClass), function (index, value) {
values += value;
});
}
用.each()循环解决此问题的大量方法。 我认为重要的是,如果您是新手,请具有非常易读的循环,否则您将很快失去跟踪。
1)全局变量
2)首先确保有人在输入中写东西时收集了数据!
3)pippo函数将清除全局变量“ arrSigle”(Array Sigle的缩写),并确保仅填充当前记录的当前数字
$(document).ready(function () {
//1
var arrSigle= [];
//2
$( ".sigle-sz" ).find("input").on("change", function(){
pippo();
//just FYI, the "change" only fires when an input has a new value, and lose focus
// by any means. If it annoys you to have to click out of the box for pippo()
//to run, you might want to use "onkeyup" instead of "change".
//it will fire every time someone lets go of a key while inside the input
})
//3
function pippo(){
arrSigle.length = 0; //this clears the variable
$( ".sigle-sz" ).find("input").each(function(){
arrSigle.push($(this).val());
//this itterates over all the inputs and pushes them into the
//global variable.
})
//If you want some function to run right after all the
//numbers has been gathered, put it right under this comment.
}
});
我们都可以讨论这有多“有效”,但是考虑到您的页面可能有多小,我认为使它变得如此简单是合理的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.