2016-02-27 27 views
1

https://jsfiddle.net/qmLpakuq/JQuery的上變化不工作的div

這裏是我的HTML:

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

,這裏是我的JQuery:

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

[onchange僅在input,select和textarea上觸發](https://developer.mozilla.org/en-US/docs/Web/Even ts/change)元素。 – Kenney

+0

如果我想檢測div上的更改怎麼辦? –

+0

那些會有什麼變化? – Kenney

回答

1

你可以使用的setInterval和clearInterval方法。設定的時間間隔將是積極的,只有當neccessary,像這樣:

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

正如評論所說,不燒成div元素onchange事件。 DOMSubtreeModified事件現在已被棄用,並使用計時器似乎有點hacky。

正確的方法做,這是通過使用MutationObserver

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

 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    if(mutation.type === 'characterData') { 
 
    \t document.write('targetNode changed:<br />'); 
 
    \t 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);
<div id="my-div">Initial Value</div>

如果需要支持超過11年長的IE版本,那麼你就需要使用填充工具: https://github.com/megawac/MutationObserver.js https://github.com/webcomponents/webcomponentsjs