开发者

jQuery .live and parent() problem

I have many of this snippet code:

<li>
  <label>
    <a title="Cadeo">
      <span class="container">
        <img class="shadow" src="../public/4cf54b32bd723_small.jpg" alt="" />
      </span>
    </a>
    <input name="Trailer" type="radio" value="1" />
    <span class="change">Seleziona</span>
  </label>
</li>

Thanks to this jQuery code, when clicking on tag (that contains all) the "Seleziona" text is replaced with a button tag:

$('label').click(function(){
  $('label').children('span.change').html('Seleziona'); // reset the others li's text
  $(this).children('span.change').html('<button type="button" class="small middle"><img src="../images/vota-small.png" alt="" /></button>')
})

Now comes the tricky part: I'm trying to catch the value of the radio input tag, but this doesn't work (I am using the .live function since the button is created at runtime)

$('button').live('click', function(){
  alert($(this).parent().siblings('input').val());
})

Where am I wrong? I keep getting "开发者_如何学运维undefined"... Thanks in advance for the answers

If it can help, here is a live version: http://jsfiddle.net/H4Gsq/


Try this -

$('button').live('click', function(e){
  e.stopPropagation();
  alert($(this).parent().prev('input').val());

})

Actually when you click button at that time that click would even propogate to label and hence labels click function will also be triggered. This effect is known as bubbling. To step event bubbling i have used e.stopPropagation()


First, why the parent()? The input is the sibling of the span, not the sibling of its parent. Second, both event handlers will fire when you click the button. stopPropagation is no help as live itself relies on event bubbling; also, live event handlers fire after normal event handlers. You should check event.target and if it is a button, skip the click handler of the label.

Forget the first part, I didn't read the code carefully. Anyway, here is a corrected version: http://jsfiddle.net/H4Gsq/1/


why not fire a custom trigger and then manipulate it accordingly...

$("input[type='radio']").trigger("checked");

$("input[type='radio']").live('checked',function(){

alert($(this).parent().prev('input').val());

})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜