当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Jquery: change attributes of button and its siblings on click

问题描述:

I have divs with buttons. If div is cover, the button's text is 'Cover' and it's disabled. Other buttons have text 'Set as cover' and are enabled. If I click on other button, it should change its text to 'Cover' and become disabled. The one that was 'Cover' should change to 'Set as cover' and become enabled.

JavaScript

function setCoverObject(id) {

var url = "{{ path('collection_set_cover', {'id' : id}) }}";

$.ajax({

url: url,

success: function (data) {

$(this).prop('disabled', true);

$(this).attr('value', 'Cover');

$(this).siblings('.set_as_cover').prop('disabled', false);

$(this).siblings('.set_as_cover').attr('value', 'Set cover');

}

});

}

Twig

{% for object in collection.objects %}

<div class="object">

<button id="cover_button_{{ object.id }}"class="set_as_cover"

onclick="setCoverObject('{{ object.id }}'); return false;">

Set cover

</button>

</div>

{% endfor %}

This code is not working, however after page reload all changes are applied.

网友答案:

Assuming that the setCoverObject is an event handler, you need to bind the AJAX callback to this value. So:

success: function (data) {
  ...
}.bind(this)

And if it is not an event handler, then find your button element and bind the callback to it. E.g.:

var button = $("#id-of-your-button").get(0)
success: function (data) {
  ...
}.bind(button)

Also to set the button text you shouldn't use the button's value attribute you should set the button content, so instead of

some_button.attr('value', 'Set cover') 

use:

some_button.text('Set cover')
网友答案:

I added id to certain button and used .not to change other buttons.

 success: function (data) {
            $('.set_as_cover').not('#cover_button_'+objId).each(function(){
                $(this).prop('disabled', false);
                $(this).text('Set cover');
            });
            $('#cover_button_'+objId).prop('disabled', true);
            $('#cover_button_'+objId).text('Cover');
        }
分享给朋友:
您可能感兴趣的文章:
随机阅读: