如何使用jquery正确地将a添加到页面并让change事件起作用?

时间:2020-03-06 14:33:47  来源:igfitidea点击:

我目前在页面上有多个选择,这些选择是使用jquery通过ajax调用动态添加的。

我遇到的问题是,除非我在标记中使用onchange,否则我无法使change事件在添加的select上起作用。

<select id="Size" size="1" onchange="onChange(this);">

这可行,但是我想知道是否有办法让jquery分配它。我已经尝试在通常的$(document).ready位置使用$('select')。change(onChange($(this));,但是没有用。

我已经尝试过在ajax调用之后添加具有bind的事件,但是那也不起作用。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

有更好的方法分配事件吗?

解决方案

$('select').change(onChange($(this));

我们需要了解调用函数和将其作为对象传递之间的区别。函数是JavaScript中的一流对象,它们与其他任何对象一样都是对象,因此它们可以存储在变量中,作为参数传递给其他函数,依此类推。

我们所拥有的代码将调用onChange函数,并将结果提供给jQuery的change函数。你不要那样这个想法是将函数本身传递给jQuery的change函数,并且jQuery在适当的时候调用它。

当在函数名称后加上括号()时,就在调用它。否则,我们会将其视为对象。因此,我们打算做的事情可以像这样完成:

$('select').change(onChange);

我有一个类似的问题,在这里找到了这个解决方案:

When you do something like this: 

$('p').click( function() { alert('blah'); } ) 

  
  All the currently existing 'p'
  elements will have a click handler
  attached.  Now if you go on to add
  other 'p' elements to the page they
  will not  have the your click handler attached to them. You would
  need to  "rerun" the

$('p').click( function() { alert('blah'); } )

  
  on the new  elements to attach the
  handlers to them. 
  
  You might like to look at the
  "LiveQuery" plugin as is manages
  all newly  added elements so they get
  the previously attached handlers
  attached  to them when they're added
  to a page.
  
  Karl Rudd

因此,在添加选择项之​​后,我们将不得不重复change()调用。

将选择添加到页面后,我们需要向其添加更改事件:

$('#newSelect').change(
    function() 
    { 
        onChange(this)
    }
);

如果我们选择的所有类都具有相同的类,则最好先取消绑定,然后再重新绑定:

$('.classname').unbind("change");
$('.classname').change(
    function() 
    { 
        onChange(this)
    }
);

谢谢大家的帮助,答案奏效了,但不是我在做什么。我终于用萤火虫弄清楚了。我试图在ajax完成操作之前分配更改事件(我们可能已经注意到,我对这种ajax工作并不陌生)。

我在load()上添加了分配给回调的事件,现在一切正常。

$(this).load('ploc002.php', {JobNumber: JobNumber, Edit: this.id}, function()
        {
            // The DOM has been changed by the AJAX call
            // Now we need to reassign the onchange events
            $('select,input').change( function()
            {
                onChange(this)
            });
        });