我一直在学习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方法作为他如何访问引发事件的元素的例子。 –