我一直在學習JavaScript得到明確,這就是爲什麼我要告訴你使用jQuery的例子,以及如何編寫相同的代碼與JS如何獲取javascript`this`元素屬性?
我必須做這樣的列表中的jQuery:
var addText = document.querySelector("#addText"),
addButton = document.querySelector("#addButton");
addText.addEventListener("keyup", function() {
if (addText.value.trim().length > 0) {
addButton.removeAttribute("disabled", false)
} else {
addButton.setAttribute("disabled", true);
}
});
var ul = document.createElement("ul");
addButton.addEventListener("click", function() {
var textVal = addText.value;
var li = document.createElement("li");
li.innerHTML = textVal + " - <span class='removeTodo' onclick='removeTodo()'>Remove</span>";
ul.appendChild(li);
addText.value = '';
addText.focus();
addButton.setAttribute("disabled", true);
});
document.body.appendChild(ul);
function removeTodo(event) {
//
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" name="" id="addText">
<input type="button" value="Add" id="addButton" disabled>
</body>
</html>
,當你上段看到我有removeTodo()函數..我想刪除li
我點擊,但這樣做之前,我要問我如何才能獲得點擊屬性(ID,類文本,父母,孩子bla bla)以及我如何刪除或添加C.拉斯(例如)?
這是非常簡單的,像這樣
$(element).on("click", function() {
$(this).attr("id");
$(this).text();
$(this).remove();
$(this).hide();
$(this).parents().attr("class");
})
一些等同物是:'this.id','this.textContent','this.parentElement.removeChild(本)','this.style.display =「none'' ,最後一個需要更多的努力。檢查https://youmightnotneedjquery.com – evolutionxbox
此外,'onclick ='removeTodo()''應該是'onclick ='removeTodo(this)''。還要考慮在JS中添加單擊事件而不是作爲屬性。 – evolutionxbox
@MichaelGeary你似乎錯過了一點--OP使用這些jQuery方法作爲他如何訪問引發事件的元素的例子。 –