javascript - HTML 列表,添加 JQuery 以交叉选择的项目。

标签 javascript jquery html

我有一个小应用程序可以将项目添加到列表中。这些项目旁边有一个按钮,我希望能够按下该按钮添加一个(文本装饰:直通)。我尝试了几种不同的方法,但似乎没有任何效果(添加项目的 Javascript、删除最后一项、向新的 li 元素添加类等。一切正常,我的问题仅在于 JQuery 部分,更多评论在代码本身上)。

HTML

<html>

<body>

<h1> Shopping List </h1>


<button id="add"> Add </button>

<input type="text" id="input" placeholder="Enter Items"> </input>

<button id="remove"> Remove Last </button>


<ul id="list">

</ul>

</body>

</html>

Js/Jq:

document.getElementById("add").addEventListener('click', function() {


var check = document.createElement("button");
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
var buttonText = document.createTextNode("Check");

newEl.className = "liEl";
newEl.appendChild(newText);
newEl.appendChild(check);
check.setAttribute("class", "checked");
check.appendChild(buttonText);


/* Problem starts here */

$("button.checked").on('click', function() {

$('li.liEl').css('text-decoration: line-through');

 /* It should get the button with the class "checked" and on click, make the li elements with class "liEl" to have that css... */

 }
);


var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";



document.getElementById('input').onkeypress = function(e) {
if (e.keyCode == 13) {
document.getElementById('add').click(); /*  adds an event listener to the submit text, keyCode 13 equals the enter key so when it's pressed it presses the add button. */
}
}
});


 /* Delete last item function: */

  document.getElementById("remove").addEventListener('click', function() {
  var els = document.getElementsByTagName("li");
  var removeEl = els[els.length - 1]; // <-- fetching last el, If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
  var containerEl = removeEl.parentNode;
  containerEl.removeChild(removeEl);
 });

最佳答案

使用 $('li.liEl').css('text-decoration','line-through');

这样的样式

关于javascript - HTML 列表,添加 JQuery 以交叉选择的项目。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408354/

相关文章:

javascript - 如何滚动到 ul 的底部?

jQuery Submit 不会提交表单

javascript - 隐藏按钮并在单击按钮时显示隐藏的 p-tag

javascript - 无法在 SVG 路径元素上执行单击事件

javascript - 如何使用 JSX 从 .map() 将 .push() 选择的 ids 到数组(本地状态)

javascript - 鼠标移出时隐藏菜单

javascript - 更改 Angular2 主 url

javascript - MomentJS 设置时区

javascript - 如何使用 Jquery 将数据发布到 iframe

php - jQuery Mobile 表单日期输入格式