简体   繁体   English

如何使用另一个按钮启用/禁用一个按钮?

[英]How do I enable/disable a button, using another button?

I'm trying to enable/disable some buttons, using another toggle button. 我正在尝试使用另一个切换按钮来启用/禁用某些按钮。

I'm trying to do it by adding a class 'active' to the buttons, and targeting only the buttons with the class. 我正在尝试通过向按钮添加“活动”类,并仅针对具有该类的按钮来做到这一点。

Here is an example (That doesn't work): 这是一个示例(不起作用):

 $('#on-off').on('click', () => { $('#test').addClass('active'); $('#indication').text('Test is active'); }); $('#test .active').on('click', () => { $('#result').text('Test was clicked!'); }); 
 <button id='on-off'>Toggle Test</button> <div id='indication'></div> <button id='test'>Test</button> <div id='result'></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The full code is here . 完整的代码在这里

You should set the disabled property to enable or disable it. 您应该将disabled属性设置为启用或禁用它。 You can use .prop() method 您可以使用.prop()方法

Also note #test .active will not work as its descendant selector and button has no child element. 另请注意, #test .active将不起作用,因为其后代选择器且按钮没有子元素。

 $('#on-off').on('click', () => { $('#test').prop('disabled', !$('#test').prop('disabled')); $('#indication').text('Test is active'); }); $('#test').on('click', () => { $('#result').text('Test was clicked!'); }); 
 <button id='on-off'>Toggle Test</button> <div id='indication'></div> <button id='test'>Test</button> <div id='result'></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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

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