如何使用jquery检测下拉列表中的选项内容更改? [英] How to detect option content change in dropdown using jquery?

查看:86
本文介绍了如何使用jquery检测下拉列表中的选项内容更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉字段,其中的选项将动态更改。
当下拉列表中的选项集发生变化时,有没有办法捕获事件?

I have a dropdown field, options of which will be changed dynamically. Is there a way to capture the event, whenever the set of options inside the dropdown is changed?

我不想捕捉期权变更,即

I do not want to capture the option change i.e

$(".dropdown").on("contentChange", function(){
    //do something
})

相反,我希望捕获事件,当下拉列表中的选项集被修改时。
如何附加处理程序,当选项集更改时,处理程序将获得触发器功能。

Rather, I want to capture the event, when the set of options inside the dropdown gets modified. How can i attach a handler, which will get trigger functions when option set changes.

推荐答案

可以观察DOM变化,在新设置的DOM规范中我们有 MutationObserver 来观察DOM 。工作示例

It is possible to watch DOM changes, in newset DOM specification we have MutationObserver to observe DOM. Working exampe

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

//create observer
var observer = new MutationObserver(function(mutations, observer) {
    
     console.log("Options have been changed");

});

//set to observe childs ( options )
observer.observe(document.querySelector(".dropdown"), {
  subtree: true,
  childList:true,
  attributes:true
});

//test change
$('button').on("click",function(){

  $(".dropdown").prepend("<option>New added option</option>");
  
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropdown">
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
  <option>Fourth</option>
</select>  
<button>Test button options change</button>

你也可以使用事件 DOMSubtreeModified 。主要浏览器上的活动工作但已弃用。工作示例:

You can use also event DOMSubtreeModified. Event work on major browsers but is DEPRECATED . Working example:

//add event    
$(".dropdown").on("DOMSubtreeModified", function(e){

  console.log('Options have been changed');

});

//change option example after button click
$('button').on("click",function(){

  $(".dropdown").prepend("<option>New added option</option>");
  
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropdown">
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
  <option>Fourth</option>
</select>  
<button>Test button options change</button>

I单击按钮后添加了一些示例选项修改。将在选择内的任何DOM更改时调用事件。

I added some example options modification after button click. Event will be called on any DOM change inside select.

这篇关于如何使用jquery检测下拉列表中的选项内容更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆