문제

I've bound an event to an icon on click. The event changes the id of a button on the page. I want a new event to be bound to that new id, and the existing event bound to the old id to be unbound. How do I do this?

I can see from Firebug that the button id successfully changes when the icon is clicked. However, when I look at POST, I see that the hidden field with id "Final_Approval" has the value of "Approved", which tells me that the event tied to the original button id occurred, and I don't want it to. All of my jQuery is inside document ready.

The original button:

<button id="btn-final-approval-no-review" class="btn btn-warning" type="submit">Final Approval</button>

The original event tied to that id:

$('[id^="btn-final-approval"]').click(function () {
    $("#Final_Approval").val("Approved");
});

The event triggered when the icon is clicked:

$("#add-vendor-item").click(function () {
   $('#btn-final-approval-no-review').attr('id', 'btn-vendor-rep-review2');
}

The new event I want to take place:

$("#btn-vendor-rep-review2").click(function () {
    $("#ItemRequestStatusId").val("@Portal.BusinessModel.Entities.ItemRequestStatusId.VendorRepReview");
});
도움이 되었습니까?

해결책

To bind events to elements that change dynamically, you need to use delegation with on():

$(document).on('click', '[id^="btn-final-approval"]', function() {
    $("#Final_Approval").val("Approved");
});

As adeneo said, you probably shouldn't move IDs around, you should use classes. But the same idea applies, you just have to change the selector in the on() call.

다른 팁

Use on delegate to bind click event dynamically.

$("body").on("click","#btn-vendor-rep-review2", function () {    
    $("#ItemRequestStatusId").val("@Portal.BusinessModel.Entities.ItemRequestStatusId.VendorRepReview");
});
$(document).on('click', '#finalApproval', function() {

if($(this).hasClass('first')){
    $(this).removeClass('first');
    //first action to be preformed    
}else{
  //second action to be preformed.
}


});

then simply add class first to the button on page load.

If you need it to toggle back you can just re-add the class first in the second action to be preformed area EDIT

after re-reading the question you probably cant use this - just substitute with the id / class of the item in question and add the if/else statement to the handler for that item.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top