我有一堆
<div class="location-box" data-location-id="123">
<img src="img_url" />
</div>
加載到我的.locationsdiv 中。我希望每當您單擊 a 時.location-box,單擊的 div 都會在其上突出顯示類。并且屬性值被添加到隱藏的輸入中。當您單擊另一個時,前一個中的類將被洗掉。等等等等。
我以前試過當那些 div 是靜態的時,它作業得很好。但現在我從 api 呼叫中將這些 div 附加到純 Javascript 之外。
我也知道尚未生成的 DOM 不能被事件監聽器等操作。
我研究了突變觀察者,并嘗試了檔案中的一些簡單內容。但我可以讓這段代碼與它一起作業
let locations = document.querySelectorAll(".location-box");
locations.forEach( el =>
el.addEventListener('click', function() {
locations.forEach( els => els.classList.remove('active-location'));
document.getElementById('location_id').value = this.getAttribute('data-location-id');
this.classList.add("active-location");
})
);
有誰知道如何使這項作業?也許不僅是這一次,而且在許多情況下。因為在不久的將來,我可能會有更多尚未生成的 DOM。
uj5u.com熱心網友回復:
從我上面的評論...
“@Coolguy31 ...
MutationObserver基于方法很可能是矯枉過正。事件委托可能是選擇的技術。但是為了以某種方式正確地實作它,很高興知道所有后來渲染的東西是否總是插入/附加到一個公共下面并且也稱為根節點,document.body因為事件監聽根也不是最優雅/高性能的選擇。”
function uuid(a) {
// [https://gist.github.com/jed/982883] - Jed Schmidt
return a
? (a^Math.random()*16>>a/4).toString(16)
: ([1e7] -1e3 -4e3 -8e3 -1e11).replace(/[018]/g,uuid);
}
function addLocations(evt) {
evt.preventDefault();
const allLocationsRoot =
document.querySelector('.locations');
allLocationsRoot.innerHTML = `
<div >
<img src="https://picsum.photos/133/100?grayscale" />
</div>
<div >
<img src="https://picsum.photos/100/75?grayscale" />
</div>
<div >
<img src="https://picsum.photos/120/90?grayscale" />
</div>
`;
allLocationsRoot
.querySelectorAll('.location-box')
.forEach(locationNode => locationNode.dataset.locationId = uuid());
allLocationsRoot
.closest('form[name="location-data"]')
.elements['location']
.value = '';
}
function initializeAddLocations() {
document
.querySelector('button')
.addEventListener('click', addLocations);
}
function handleLocationSelect(evt) {
const locationItemRoot = evt
.target
.closest('.location-box');
if (locationItemRoot) {
const allLocationsRoot = locationItemRoot
.closest('.locations');
const locationControl = allLocationsRoot
.closest('form[name="location-data"]')
.elements['location'];
// console.log({
// target: evt.target,
// locationItemRoot,
// allLocationsRoot,
// locationControl,
// });
allLocationsRoot
.querySelectorAll('.location-box')
.forEach(locationNode => locationNode.classList.remove('selected'));
locationItemRoot.classList.add('selected');
locationControl.value = locationItemRoot.dataset.locationId;
}
}
function initializeLocationHandling() {
document
.querySelector('.locations')
.addEventListener('click', handleLocationSelect)
}
function main() {
initializeLocationHandling();
initializeAddLocations();
}
main();
body { margin: 0; }
[type="text"][name="location"] { width: 23em; }
.locations:after { display: block; content: ''; clear: both; }
.location-box { float: left; margin: 4px; padding: 10px; min-height: 104px; background-color: #eee; }
.location-box.selected { outline: 2px solid #fc0; }
<form name="location-data">
<div class="locations">
</div>
<button>update locations</button>
<!--
<input type="hidden" name="location" />
//-->
<input type="text" name="location" disabled />
</form>
uj5u.com熱心網友回復:
您可以使用 來執行此操作MutationObserver,代碼如下所示,它沒有獲取屬性的部分,但您可以添加它,另一種方法就像@scara9 所說,在您使用的代碼上渲染每個.location-box你可以分配點擊處理程式。
在下面的代碼中,我使用 jquery 來“添加”新location-box的,你不需要 jquery
// select the parent node: .locations, i switched to ID for test
var target = document.getElementById("locations");
// create an observer instance
var observer = new MutationObserver(function (mutations) {
//loop through the detected mutations(added controls)
mutations.forEach(function (mutation) {
//addedNodes contains all detected new controls
if (mutation && mutation.addedNodes) {
mutation.addedNodes.forEach(function (elm) {
if (elm && elm.className=="location-box") {
elm.addEventListener("click", function () {
elm.classList.add("active-location");
var locations = document.querySelectorAll(".location-box");
locations.forEach((e) => {
if (e != elm) {
//ignore clicked element
e.classList.remove("active-location");
}
});
});
}
});
}
});
});
// pass in the target node, as well as the observer options
observer.observe(target, {
childList: true
});
//you don't need this, it's only to simulate dynamic location-box
$(function () {$("button").on("click", function () {var count = $(".location-box").length 1;$(".locations").append($("<div class='location-box' data-attribute-id='" count "'>location box:" count "</div>"));});});
.active-location{
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="locations" id="locations">
</div>
<!-- This button it's only to add the controls, not needed in your case-->
<button type="button" id="add">
Add
</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422067.html
標籤:
上一篇:如何影片兩個字母交換?
下一篇:對Div中的數字進行數字排序
