jQuery Event : div의 html/text 변경사항 탐지
는 항상.ajax requests,jquery functions,blur등
언제든지 디브의 변화를 감지할 수 있는 방법이 있습니까?
선택한 간격이나 기본값을 사용하지 않습니다.
이런 식으로 하면 됩니다.
$('mydiv').contentchanged() {
alert('changed')
}
원하지 않으면 타이머를 사용하고 내부를 확인합니다.HTML 당신은 이 이벤트를 시도할 수 있습니다.
$('mydiv').on('DOMSubtreeModified', function(){
console.log('changed');
});
자세한 내용 및 브라우저 지원 데이터는 여기에 있습니다.
Javascript Mutation Observer 사용:
// Select the target node.
var target = document.querySelector('mydiv')
// Create an observer instance.
var observer = new MutationObserver(function(mutations) {
console.log(target.innerText);
});
// Pass in the target node, as well as the observer options.
observer.observe(target, {
attributes: true,
childList: true,
characterData: true
});
자세한 내용은 MDN 설명서를 참조하십시오. IE11을 포함한 거의 모든 현재 브라우저에서 작동합니다.
는 더 이상 사용되지 않으므로 다음을 사용해야 합니다.
$("body").on('DOMSubtreeModified', "#selector", function() {
// code here
});
해보세요.
$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {
});
하지만 이것은 인터넷 익스플로러에서 작동하지 않을 수도 있습니다, 테스트하지 않았습니다.
변환 관찰자 또는 변환 이벤트를 찾고 있습니다.어느 곳에서나 지원되지 않으며 개발자 세계에서도 그다지 좋게 보지 않습니다.
만약 당신이 div의 크기가 변경될 것이라는 것을 알고 있다면, 당신은 크로스 브라우저 크기 조정 이벤트를 사용할 수 있을 것입니다.
다음 코드를 사용할 수 있습니다.
$("body").on('DOMSubtreeModified', "mydiv", function() {
alert('changed');
});
이 문제에 대한 내장 솔루션은 없습니다. 설계 및 코딩 패턴의 문제입니다.
게시자/가입자 패턴을 사용할 수 있습니다.이를 위해 jQuery 사용자 정의 이벤트 또는 자체 이벤트 메커니즘을 사용할 수 있습니다.
첫번째,
function changeHtml(selector, html) {
var elem = $(selector);
jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
elem.html(html);
jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}
이제 다음과 같이 divhtmlchange/divhtmlchange 이벤트를 구독할 수 있습니다.
$(document).bind('htmlchanging', function (e, data) {
//your before changing html, logic goes here
});
$(document).bind('htmlchanged', function (e, data) {
//your after changed html, logic goes here
});
이제, 당신은 이것을 통해 당신의 div 콘텐츠를 바꿔야 합니다.changeHtml()기능 data 인수로 인해 할 수 .따라서 정보가 포함된 bind callback data 인수를 통해 필요한 변경사항을 모니터링하거나 수행할 수 있습니다.
당신은 당신의 div의 html을 이렇게 바꿔야 합니다;
changeHtml('#mydiv', '<p>test content</p>');
또한 입력 요소를 제외한 모든 HTML 요소에 사용할 수 있습니다.모든 요소에 사용할 수 있도록 수정할 수 있습니다.
Mozilla에서 제공하는 이 스니펫에 표시된 대로 MutationObserver를 사용하고 이 블로그 게시물에서 수정합니다.
또는 이 링크에 표시된 JQuery 예제를 사용할 수 있습니다.
Chrome 18+, Firefox 14+, IE 11+, Safari 6+
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
위에 제시된 답변 중 일부를 시도했지만 그 화재 사건은 두 번 발생했습니다.만약 당신이 같은 것이 필요하다면, 여기 작동하는 해결책이 있습니다.
$('mydiv').one('DOMSubtreeModified', function(){
console.log('changed');
});
오래된 내부를 보관할 수 있습니다.변수에 있는 div의 HTML입니다.이전 내용이 현재 내용과 일치하는지 확인할 간격을 설정합니다.이것이 사실이 아닐 때는 뭔가를 하라.
Mutation Observer를 사용해 보십시오.
- https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/
- https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
브라우저 지원: http://caniuse.com/ #http=httpserver
<html>
<!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// Inspect the array of MutationRecord objects to identify the nature of the change
function mutationObjectCallback(mutationRecordsList) {
console.log("mutationObjectCallback invoked.");
mutationRecordsList.forEach(function(mutationRecord) {
console.log("Type of mutation: " + mutationRecord.type);
if ("attributes" === mutationRecord.type) {
console.log("Old attribute value: " + mutationRecord.oldValue);
}
});
}
// Create an observer object and assign a callback function
var observerObject = new MutationObserver(mutationObjectCallback);
// the target to watch, this could be #yourUniqueDiv
// we use the body to watch for changes
var targetObject = document.body;
// Register the target node to observe and specify which DOM changes to watch
observerObject.observe(targetObject, {
attributes: true,
attributeFilter: ["id", "dir"],
attributeOldValue: true,
childList: true
});
// This will invoke the mutationObjectCallback function (but only after all script in this
// scope has run). For now, it simply queues a MutationRecord object with the change information
targetObject.appendChild(document.createElement('div'));
// Now a second MutationRecord object will be added, this time for an attribute change
targetObject.dir = 'rtl';
</script>
</body>
</html>
DOM 하위 트리 수정은 좋은 해결책이 아닙니다.이벤트 핸들러 내에서 DOM을 변경하기로 결정하면 무한 루프가 발생할 수 있으므로 여러 브라우저에서 DOM을 사용할 수 없습니다.MutationObserver가 더 나은 답입니다.
const onChangeElement = (qSelector, cb)=>{
const targetNode = document.querySelector(qSelector);
if(targetNode){
const config = { attributes: true, childList: false, subtree: false };
const callback = function(mutationsList, observer) {
cb($(qSelector))
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}else {
console.error("onChangeElement: Invalid Selector")
}
}
그리고 당신은 이렇게 사용할 수 있습니다.
onChangeElement('mydiv', function(jqueryElement){
alert('changed')
})
jQuery를 통해 또는 de DOM-API를 통해 div에 일부 콘텐츠를 추가하는 것은 기본적으로.appendChild()기능.당신이 할 수 있는 것은 그것을 무시하는 것입니다..appendChild()현재 객체의 기능 및 그 안에 관찰자를 구현합니다.이제 우리의 것을 무시했습니다..appendChild()기능, 우리는 다른 객체로부터 그 기능을 빌려야 내용을 추가할 수 있습니다.그래서 우리는 그것을 부릅니다..appendChild()다른 디비가 마침내 내용을 추가합니다.물론, 이것은 또한 중요합니다..removeChild().
var obj = document.getElementById("mydiv");
obj.appendChild = function(node) {
alert("changed!");
// call the .appendChild() function of some other div
// and pass the current (this) to let the function affect it.
document.createElement("div").appendChild.call(this, node);
}
};
여기서 naïf 예를 찾을 수 있습니다.제 생각에는 당신이 직접 연장할 수 있을 겁니다.http://jsfiddle.net/RKLmA/31/
참고로 이것은 JavaScript가 OpenClosed 원칙을 준수한다는 것을 보여줍니다.:)
언급URL : https://stackoverflow.com/questions/15657686/jquery-event-detect-changes-to-the-html-text-of-a-div
'source' 카테고리의 다른 글
| res.end()와 res.send()의 차이점은 무엇입니까? (0) | 2023.05.20 |
|---|---|
| NSLog에서 부울 플래그를 인쇄하는 방법은 무엇입니까? (0) | 2023.05.20 |
| Office Open XML Cell에 날짜/시간 값이 포함되어 있음을 나타내는 것은 무엇입니까? (0) | 2023.05.20 |
| Git에서 손실된 저장소를 복구하려면 어떻게 해야 합니까? (0) | 2023.05.20 |
| Excel 파일(.xlsx)에 데이터를 쓰는 방법 (0) | 2023.05.20 |