I'm trying to understand how to use bind in jquery.
I have a page which, after a button press, does the following code:
var html = [];
html.push('<select name="weddingturn" id="weddingturn">');
var a = firstweddingturn;
var b = Number(firstweddingturn) + 16;
while (a < b) {
// do some code
html.push('<option name="asdf">' + a + '</option>');
a++;
} // end while
html.push('</select>');
$('#div1').append(html.join(''));
I also want to catch any changes to that select, once it is set up.
var firstweddingturn = '400';
$('#weddingturn').live('change',function() {
alert ("Wedding select change triggered!");
//var wedturn = $('#weddingturnselectid').val();
//$('#div3').append('<br>Wedding turn selected, ' + wedturn + '</br>')
});
I 开发者_开发技巧would greatly appreciate someone showing and explaining how to use bind() in this instead of live().
For context sake, please see here: jquery created select, and triggering on change
Just swap:
$('#weddingturn').live('change',function() {
to:
$('#weddingturn').bind('change',function() {
.live
should've solved your problem - so what is the exact reason or problem you're having?
There is also a shorthand for bind() for certain events. You can make your code shorter by doing:
$('#weddingturn').change(function() {
Keep in mind though that bind()
and live()
do fundamentally different things. live()
affects everything with the given selectors, while bind()
will only bind events to elements that are already on the page.
$('#weddingturn').live('change',function(){});
This site explains the difference very well: http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
I think it depends on when you are calling live or bind - after or before those html element available. If you are calling bind after those html element is available on that page, it should be OK to swap. Otherwise, I think bind would not work.
精彩评论