Hướng dẫn javascript listen attribute change - thay đổi thuộc tính nghe javascript

Có thể trong JavaScript để lắng nghe để thay đổi giá trị thuộc tính? Ví dụ:

var element=document.querySelector('…');
element.addEventListener( ? ,doit,false);

element.setAttribute('something','whatever');

function doit() {

}

Tôi muốn trả lời bất kỳ thay đổi nào trong thuộc tính something.

Tôi đã đọc trên đối tượng MutationObserver, cũng như các lựa chọn thay thế cho điều đó (bao gồm cả một trong đó sử dụng các sự kiện hoạt hình). Theo như tôi có thể nói, họ là về những thay đổi đối với DOM thực tế. Tôi quan tâm nhiều hơn đến các thay đổi thuộc tính đối với một yếu tố DOM cụ thể, vì vậy tôi không nghĩ rằng đó là nó. Chắc chắn trong thử nghiệm của tôi, nó dường như không hoạt động.

Tôi muốn làm điều này mà không cần jQuery.

Cảm ơn

Hướng dẫn javascript listen attribute change - thay đổi thuộc tính nghe javascript

Đã hỏi ngày 2 tháng 1 năm 2017 lúc 10:25Jan 2, 2017 at 10:25

Hướng dẫn javascript listen attribute change - thay đổi thuộc tính nghe javascript

1

Bạn cần đột biến trình điều khiển, ở đây trong đoạn trích tôi đã sử dụng

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
0 để mô phỏng thuộc tính sửa đổi

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
Dummy Text

GầnHusCarl

49,8K12 Huy hiệu vàng198 Huy hiệu bạc177 Huy hiệu đồng12 gold badges198 silver badges177 bronze badges

Đã trả lời ngày 2 tháng 1 năm 2017 lúc 10:30Jan 2, 2017 at 10:30

Hướng dẫn javascript listen attribute change - thay đổi thuộc tính nghe javascript

SatpalsatpalSatpal

Huy hiệu vàng 131K1313 gold badges154 silver badges166 bronze badges

3

Câu hỏi này đã được trả lời, nhưng tôi muốn chia sẻ kinh nghiệm của mình, bởi vì người quan sát đột biến đã không mang đến cho tôi những hiểu biết cần thiết.

Lưu ý đây là một số loại giải pháp hacky, nhưng đối với mục đích gỡ lỗi (ít nhất) khá tốt. This is some kind of hacky solution, but for (at least) debugging purposes quite good.

Bạn có thể ghi đè chức năng

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
1 của phần tử particalar. Bằng cách này, bạn cũng có thể in CallStack và hiểu rõ hơn về "WHO" đã thay đổi giá trị thuộc tính:

// select the target element
const target = document.querySelector("#element");
// store the original setAttribute reference
const setAttribute = target.setAttribute;
// override setAttribte
target.setAttribute = (key: string, value: string) => {
  console.trace("--trace");
  // use call, to set the context and prevent illegal invocation errors
  setAttribute.call(target, key, value); 
};

Đã trả lời ngày 12 tháng 4 lúc 7:01Apr 12 at 7:01

Hướng dẫn javascript listen attribute change - thay đổi thuộc tính nghe javascript

Scipperscipperscipper

2.7642 Huy hiệu vàng19 Huy hiệu bạc37 Huy hiệu đồng2 gold badges19 silver badges37 bronze badges

Thật tốt khi có người nghe sự kiện cho các sự kiện trên các yếu tố, nhưng làm thế nào để bạn lắng nghe một cái gì đó giống như một thay đổi thuộc tính?

Nhập MutationObserver. Một trong những phẩm chất tốt nhất của nó là cho phép bạn khả năng xem dữ liệu không có khả năng được nghe, giống như một sự kiện DOM truyền thống.

Đầu tiên, thiết lập chức năng sẽ được gọi bởi MutationObserver. Chỉ cần một đối số:

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
4. Mỗi mục trong danh sách là những gì mà người ta gọi là
var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
5. Cuộc gọi lại có thể làm bất cứ điều gì bạn muốn.

const mutationCallback = (mutationsList) => {
for (const mutation of mutationsList) {
if (
mutation.type !== "attributes" ||
mutation.attributeName !== "data-foo"
) {
return
}
console.log('old:', mutation.oldValue)
console.log('new:', mutation.target.getAttribute("data-foo"))
}
}

Tiếp theo, MutationObserver thực hiện cuộc gọi lại của bạn khi khởi tạo phiên bản:

const observer = new MutationObserver(mutationCallback)

Tất nhiên, chúng tôi đã thực sự khởi động người quan sát. Chỉ cần gọi phương thức

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
7 trên biến mới của bạn. Các đối số của nó là yếu tố cần quan sát và một đối tượng mô tả dữ liệu mà bạn đang quan sát:

observer.observe(myElement, { attributes: true })

Cuối cùng, bạn có thể ngừng quan sát các thay đổi bằng phương pháp

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
8:

observer.disconnect()

Và đó là nó. Dễ dàng, phải không? Vâng, chỉ cần cẩn thận; Nó có thể hấp dẫn để tạo ra các nhà quan sát đột biến mới cho mọi điều nhỏ nhặt. Thay vào đó, hãy cố gắng củng cố càng nhiều càng tốt vào một người quan sát. Bạn có thể thêm

var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
9 khi gọi phương thức
var element = document.querySelector('#test');
setTimeout(function() {
  element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === "attributes") {
      console.log("attributes changed")
    }
  });
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});
7 để lắng nghe các thay đổi cho các nút con!

Kiểm tra đầy đủ các tùy chọn cho dữ liệu có thể quan sát được ở đây.

Nếu bạn thích những gì bạn đọc, hãy thoải mái xóa bỏ nút đó. ✅

George là một nhà phát triển đầu tiên và nhà thiết kế kỹ thuật số sống ở Oregon. Ban ngày, anh ấy là một kỹ sư phần mềm trong nhóm hệ thống thiết kế ServiceNow. Vào ban đêm, anh ta liên tục sắp xếp lại bộ sưu tập trò chơi video của mình như một sự phân tâm từ cuối cùng chơi một.