开发者

I want to get a specific parent node of an element use jQuery but it's not working for some reason

I have a span inside a legend tag that I want to use to remove the fieldset tag when clicked. I'm using jQuery and this is the code that I can't seem to get to work: (yes, i'm using latest version of jQuery)

jQuery:

function removeStep(){
        $(t开发者_如何学编程his).closest("fieldset").remove();
        //Already tried: $(this).parents("fieldset").remove(); . . . didn't work
}

HTML:

<div id="steps">
       <fieldset class="step">
              <legend>STEP 1: <span class="remove" onclick="removeStep();">remove</span></legend>                           
       </fieldset>
</div>


The problem is that "this" in your function won't be what you want it to be.

Since you're using jQuery anyway, you should get out of the habit of binding event handlers directly through the HTML markup like that. Instead, set up the handler with jQuery:

$(function() {
  $('span.remove').click(removeStep);
});

If you absolutely must do it in the HTML, then try this:

... <span class='remove' onclick='removeStep.call(this);'>remove</span>


$(this.parentElement.parentElement).remove() ought to work.

$(this).parent().parent().remove() is more the 'jQuery way' I suppose; I think the old IEs used parentNode instead of parentElement for some silly reason.


got it working by passing in reference to the span directly:

jQuery:

function removeStep(step){
        $(step).closest("fieldset").remove();
}

HTML:

<div id="steps">
       <fieldset class="step">
              <legend>STEP 1: <span class="remove" onclick="removeStep(this);">remove</span></legend>                           
       </fieldset>
</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜