[英]Javascript to jQuery convert code
我在更改以下代碼以使用jQuery時遇到困難。 有人能指出我正確的方向嗎?
function addListItem() {
var listItem, container, dataList = document.getElementById('dataList');
// Create our list item
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', 'images/icons/icon11.png');
listItem.setAttribute('data-bb-title', 'Title ');
listItem.innerHTML = 'My description';
// Create a dummy container
container = document.createElement('div');
container.appendChild(listItem);
// Apply the styling
bb.imageList.apply([container]);
// Append the item
dataList.appendChild(container.firstChild);
// re-compute the scrolling area
if (bb.scroller) {
bb.scroller.refresh();
}
}
首先,讓我告訴您,您的代碼看起來很好。
現在,要使用jQuery通過元素ID選擇元素,請使用ID選擇器(“ #id”) 。 因此,您可以使用以下方法來代替使用document.getElementById("dataList")
:
$("#dataList")
要動態創建DOM元素,請使用jQuery( html, props )
。 例如,要創建列表項,請使用:
listItem = $("<div />", {
data-bb-type: 'item',
data-bb-img: 'images/icon/icon11.png',
data-bb-title: 'Title'
}).html("My description");
最后,要將元素追加到另一個元素,請使用.append()
。 使用此功能,可以使用以下方法完成虛擬元素的創建:
container = $("<div />").append(listItem);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.