关于改变的JQuery没有在div上工作

时间:2016-02-27 22:42:58

标签: jquery

https://jsfiddle.net/qmLpakuq/

这是我的HTML:

<div class="info-price" id='newrange'></div>

这是我的JQuery:

$( document).on( "change", ".info-price" ,function() {
    console.log("umerjaved");
});

2 个答案:

答案 0 :(得分:1)

您可以使用setInterval和clearInterval方法。设置间隔仅在必要时才有效,如下所示:

var infoPrice = $('.info-price').html();
var infoPrice_changeFirers = $('.square').add('.infobox').add('#pr-slider');
var my_interval = null;

$(infoPrice_changeFirers).on('mousedown', function(){
    my_interval = check_infoPrice();
});

$(infoPrice_changeFirers).on('mouseup', function() {
    clearInterval(my_interval)
});

function check_infoPrice(){
  my_interval = setInterval(function(){ 
  var current_infoPrice = parseInt($('.info-price').html());
   if(parseInt(infoPrice) != current_infoPrice){
     on_infoPrice_change();
     infoPrice = $('.info-price').html();
   } 
  }, 50);
  return my_interval;
}

function on_infoPrice_change(){ // place your code here
  alert('hello');
}

答案 1 :(得分:1)

正如评论中所述,onchange元素未被div个事件触发。 DOMSubtreeModified事件现在已被弃用,使用计时器似乎有点笨拙。

执行此操作的正确方法是使用MutationObserver

&#13;
&#13;
var targetNode = document.getElementById('my-div');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if(mutation.type === 'characterData') {
    	document.write('targetNode changed:<br />');
    	document.write('Was: ' + mutation.oldValue + '<br />');
        document.write('Now: ' + targetNode.innerHTML);
    }
  });
});

observer.observe(targetNode, {
  characterData: true,
  characterDataOldValue: true,
  subtree: true
});

// Make a change one second after the page is loaded to trigger the observer.
setTimeout(function() {
  targetNode.innerHTML = 'New Value';
}, 1000);
&#13;
<div id="my-div">Initial Value</div>
&#13;
&#13;
&#13;

如果您需要支持早于11的IE版本,那么您需要使用polyfill: https://github.com/megawac/MutationObserver.js https://github.com/webcomponents/webcomponentsjs