html数据属性在firefox中使用javascript时没有按预期显示,但在chrome中显示正确

html data attribute not showing as expected when using javascript in firefox but correctly in chrome

本文关键字:显示 但在 chrome firefox 数据属性 html javascript      更新时间:2023-11-08

我希望得到以下代码:

var data = "data-detail='{" + "'id': '1', 'name': 'iPad 2', 'price': '599.00', 'quantity': '5', 'photo': 'somepath/anotherpath/photo.jpg', 'description': 'A white iPad 2'" + "}'";
string += "<section class='homeItem' " + data + "><div class='imageContainer'><img class='resultsImage' src='" + results[i].Photo + "'></div><p class='resultsName'>" + results[i].Name + "</p><p class='resultsPrice'>£" + price.toFixed(2) + "</p></section>";

在检查器中显示如下:

<section class="homeItem" data-detail="{" id':="" '1',="" 'name':="" 'ipad="" 2',="" 'price':="" '599.00',="" 'quantity':="" '5',="" 'photo':="" 'somepath="" anotherpath="" photo.jpg',="" 'description':="" 'a="" white="" ipad="" 2'}'=""><div class="imageContainer"><img class="resultsImage" src="Images/Products/macbookAir.png"></div><p class="resultsName">MacBook Air</p><p class="resultsPrice">£899.00</p></section>

这是镀铬的。但在FireFox中,它显示如下:

<section class="homeItem" 2'}'="" ipad="" white="" 'a="" 'description':="" photo.jpg',="" anotherpath="" 'somepath="" 'photo':="" '5',="" 'quantity':="" '599.00',="" 'price':="" 2',="" 'ipad="" 'name':="" '1',="" id':="" data-detail="{"></section>

有人能解释为什么会这样吗,以及它是否能以与

相同的方式工作吗

我已经通过使用以下代码修复了这个问题:

var sec = document.createElement("section");
sec.classList.add("homeItem");
sec.dataset.detail = "{'id': '1', 'name': 'iPad 2', 'price': '599.00', 'quantity': '5', 'photo': 'somepath/anotherpath/photo.jpg', 'description': 'A white iPad 2'}";
article.appendChild(sec);
相关文章: