当元素被启用/禁用时触发function

这似乎是一个相对简单的事情,但我无法在任何地方找到任何关于如何做到这一点。 我有一个模式,在等待异步数据时打开一个禁用的输入。 我想知道什么时候输入启用,我可以集中输入。 这就是我想要完成的。 将其视为全局模态打开处理程序:

$('.modal').on('shown.bs.modal', function (event) { var textInput = $(event.target).find('input[type=text]:visible').first(); if (textInput.is(':disabled')) { textInput.on('<<<<>>>>', function(){ textInput.off('<<<<>>>>'); textInput.focus(); }); } else { textInput.focus(); } }); 

输入启用/禁用时是否没有触发事件?

  0"> 

如果在异步请求中返回了用户,则会启用该function。

不幸的是,没有onenabledondisabled听众这样的东西。 输入字段只能在页面加载后由JavaScript启用/禁用(或者某些用户在开发人员工具的检查器中弄乱了HTML)。 因此, 如果要检测这些更改,则必须使用MutationObserver ,并侦听所需元素的属性突变,以便在将disabled属性添加到输入字段时进行检查。

这是我正在谈论的一个例子:

 var btn = document.getElementById('toggle'), input = document.getElementById('inp'); // This is just to demonstrate the behavior of the MutationObserver btn.addEventListener('click', function() { if (input.disabled) input.disabled = false; else input.disabled = true; }); var observer = new MutationObserver(function(mutations) { for (var i=0, mutation; mutation = mutations[i]; i++) { if (mutation.attributeName == 'disabled') { if (mutation.target.disabled) { // The element has been disabled, do something alert('You have disabled the input!'); } else { // The element has been enabled, do something else alert('You have enabled the input!'); } } }; }); // Observe attributes change observer.observe(input, {attributes: true}); 
 

Try clicking the button to disable/enable the input!

我知道这不是最好的方法,但我在这里 :

 var timeToCheck = 1000, past = 0; function wait_enable (element) { var timer = setInterval(function(){ if(element.is(":enabled")){ element.focus(); clearInterval(timer); } /* //here you can set a limit past += timeToCheck; if (past > limit) { clearInterval(timer); } */ }, timeToCheck); } var textInput = $("input"); wait_enable(textInput); $("button").on("click", function(){ textInput.prop("disabled", false); }); 

我曾经有过一个项目,但我失去了这样做的动力。 我搜索了一种方法来做这种事情,我发现MutationObserver应该是一个很好的方法。

看看: MutationObserver

也许也有: Mutation Events

我希望我能正确理解你的问题。