[英]Compare data attributes of dynamically created elements with JQuery
我正在做一個游戲,在您單擊圖像后,它會重新排列數組並重新填充DOM。 這樣的想法是即使陣列中的圖像被混洗,您也不能兩次單擊同一圖像。
的HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Document</title>
</head>
<body>
<!-- Tribute to Tom Whalen for the awesome Transformers pictures -->
<button id="shuffleButton" type="submit">Shuffle</button>
<div id="test"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="app.js">
</script>
</body>
</html>
#testDiv
會在頁面加載時填充,並且每次單擊時都會#testDiv
排列數組並重新填充#testDiv
。
對象中的每個圖像都有一個與角色圖像相關的name屬性。 我正在使用變形金剛。
這是我正在使用的對象數組的示例。
var images = [
{
name: "bumblebee",
image: "assets/images/bumblebee.jpg"
},
{
name: "frenzy",
image: "assets/images/frenzy.jpg"
}];
的JavaScript
/*Working for loop through images array */
function loop() {
for (var i =0; i < images.length; i++) {
var testImage = $('<img class="images">')
.attr('src', `${images[i].image}`)
.attr('data', `${images[i].name}`);
$(testDiv).append(testImage);
};
};
loop();
function Shuffle() {
images.sort(function(a, b) {
return 0.5 - Math.random()
});
loop();
};
$("#shuffleButton").on('click', function(){
$(testDiv).empty();
Shuffle();
console.log(images);
});
var count = 0;
$(document).on('click', '.images', function() {
$(testDiv).empty();
Shuffle();
console.log($(this).data());
});
我正在將name屬性分配給數據屬性,並想將數據屬性與click函數進行比較。
當我console.log($(this).data());
我得到一個帶有___proto___ : Object
的空白對象___proto___ : Object
而不是data屬性。 我將如何獲取數據屬性? 然后如何將其存儲到變量中? 如何將變量內的數據屬性與另一個元素的數據屬性進行比較?
您將需要為console.log函數發送數據屬性名稱。
console.log($(this).data('name'));
我在下面附上一個例子。
$(document).on('click', '#div', function() { alert($(this).data('id')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div" data-id="test" >hello</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.