为什么我需要在jquery中使用双onClick事件?
我需要澄清以下几点 为什么需要将为什么我需要在jquery中使用双onClick事件?,jquery,function,onclick,each,Jquery,Function,Onclick,Each,我需要澄清以下几点 为什么需要将onClick事件指定两次?(当我这样做时,它做我想做的事情)一次在$('.modal')。每个(function()函数中,一次在$('.window-'+counter)中。查找('input')。每个函数 如果我只使用第一个onClick函数,那么console.log将返回屏幕上所有表单的所有输入id 当我只使用最后一个onClick函数时,console.log不会返回任何内容 我试图从我的模式屏幕中获取单独的输入 $( document ).r
onClick
事件指定两次?(当我这样做时,它做我想做的事情)一次在$('.modal')。每个(function()
函数中,一次在$('.window-'+counter)中。查找('input')。每个
函数
如果我只使用第一个onClick
函数,那么console.log
将返回屏幕上所有表单的所有输入id
当我只使用最后一个onClick
函数时,console.log
不会返回任何内容
我试图从我的模式屏幕中获取单独的输入
$( document ).ready(function() {
$('.modal').each(function() {
//THIS PART-------------------------------------
$(this).on('click', function() {
//----------------------------------------------
if($( '.window-'+counter ).has('input:text').length) {
//console.log('first');
$('.window-'+counter).find('input').each(function() {
//AND THIS PART---------------------------------------------
$(this).on('click', function() {
//----------------------------------------------------------
console.log($(this).attr('id'));
});
});
};
});
});
});
这是我的HTML
<div class="modal window-1" id="modal-window"">
<div class="modal-body">
<input class="form-control" id="sku" name="sku" type="text" value="">
<input class="form-control" id="name" name="name" type="text" value="">
</div>
</div>
我测试了你的代码,发现了两件事
1) id为“modal window”的HTML div有1个不必要的双引号
2) 不清楚在哪里为“计数器”变量赋值。也许这是主要的问题
否则就不必使用onClick事件2次。如果我从$('.modal')中得到“counter”变量,那么每个循环我对这段代码和您的HTML都没有问题
$( document ).ready(function() {
//$('.modal').each(function() {
$('.modal').each(function(modalWindowIndex,modalWindow) {
counter = modalWindowIndex + 1; //your html modal window has class window-1, but jQuery each() index starts with 0
if($( '.window-'+counter ).has('input:text').length) {
$('.window-'+counter).find('input').each(function() {
$(this).on('click', function() {
console.log($(this).attr('id'));
});
});
};
});
});
我知道了,我有一个计数器,但它在另一个函数中,但是如果我理解正确的话,每次都会运行.modal?(因为“counter=ModalWindowIndex+1”)是的,所以每个()函数都会针对每个元素运行,并提供选择器(在您的示例中,元素的类为“modal”)。在代码中有两个嵌套的each()函数。Outer each()使用类“modal”遍历所有元素。internal each()使用类“.window-”+counter遍历元素中的所有输入元素。若计数器和外循环无关,那个么嵌套这两个each()循环就并没有意义了。在文档中查找更多信息