简体   繁体   English

jQuery:单击时更改按钮及其同级的属性

[英]Jquery: change attributes of button and its siblings on click

I have divs with buttons. 我有带按钮的div。 If div is cover, the button's text is 'Cover' and it's disabled. 如果div是Cover,则按钮的文本为“ Cover”,并且已被禁用。 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 的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. 假设setCoverObject是事件处理程序,则需要将AJAX回调绑定到this值。 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. 如果它不是事件处理程序,请找到您的button元素并将回调绑定到该元素。 Eg: 例如:

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 另外,要设置按钮文本,您不应该使用按钮的value属性,而是应该设置按钮内容,因此

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. 我将ID添加到某些按钮,并使用.not更改其他按钮。

 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');
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM