使用jQuery侦听器检测div内的类更改

时间:2018-12-27 17:48:30

标签: javascript jquery listener addeventlistener

这是我的默认代码。我想向.variations_div > .select-items > div添加一个侦听器。基本上,我的选择已替换为div。我想使用select onchange,但现在无法使用。这是我的原始HTML。

<div class="custom-select variations_div">
   <select>
      <option value="">- Select Variation -</option>
      <option value="9298">EXT SOCKET 1/2 X 1/2 X 10MM</option>
      <option value="9299">EXT SOCKET 1/2 X 1/2 X 15MM</option>
      <option value="9300">EXT SOCKET 1/2 X 1/2 X 20MM</option>
      <option value="9301">EXT SOCKET 1/2 X 1/2 X 25MM</option>
   </select>
   <div class="select-selected">- Select Variation -</div>
   <div class="select-items select-hide">
      <div>- Select Variation -</div>
      <div>EXT SOCKET 1/2 X 1/2 X 10MM</div>
      <div>EXT SOCKET 1/2 X 1/2 X 15MM</div>
      <div>EXT SOCKET 1/2 X 1/2 X 20MM</div>
      <div>EXT SOCKET 1/2 X 1/2 X 25MM</div>
   </div>
</div>

基本上,当我更改选择时,它会向div添加一个类same-as-selected。我希望收听者提取该特定div的html并将其提供给我。

<div class="custom-select variations_div">
   <select>
      <option value="">- Select Variation -</option>
      <option value="9298">EXT SOCKET 1/2 X 1/2 X 10MM</option>
      <option value="9299">EXT SOCKET 1/2 X 1/2 X 15MM</option>
      <option value="9300">EXT SOCKET 1/2 X 1/2 X 20MM</option>
      <option value="9301">EXT SOCKET 1/2 X 1/2 X 25MM</option>
   </select>
   <div class="select-selected">EXT SOCKET 1/2 X 1/2 X 15MM</div>
   <div class="select-items select-hide">
      <div>- Select Variation -</div>
      <div>EXT SOCKET 1/2 X 1/2 X 10MM</div>
      <div class="same-as-selected">EXT SOCKET 1/2 X 1/2 X 15MM</div>
      <div>EXT SOCKET 1/2 X 1/2 X 20MM</div>
      <div>EXT SOCKET 1/2 X 1/2 X 25MM</div>
   </div>
</div>

这是我当前的代码。

$(".variations_div > .select-items > div").attrchange({
    trackValues: true, // set to true so that the event object is updated with old & new values
    callback: function(evnt) {
        alert(1);
        if(evnt.attributeName == "class") { // which attribute you want to watch for changes
            if(evnt.newValue.search(/open/i) == -1) { // "open" is the class name you search for inside "class" attribute

                // your code to execute goes here...
            }
        }
    }

但这不起作用。

1 个答案:

答案 0 :(得分:-2)

change在这里起作用:JSFiddle