如何在javascript中为ul创建动态点击事件监听器

时间:2018-02-23 21:07:34

标签: javascript jquery html css

我有一个ul(无序列表),包含很多li。 li是动态创建的。因此,需要动态实现click事件侦听器。这在jQuery中很容易做到;

{r, results = 'asis', echo = F}
output <- "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
output

然而,我希望我的应用程序完全在javascript中。如果有人可以提供答案。赞赏 继承人在线应用程序 http://pctechtips.org/apps/todo/ inde.html

$(document).on("click", ".checkboxes", function() {     
   var boxId = $(this).attr("id");
   var num = boxId.split("-")[1];
   console.log("checkbox: "+num);
  // checkedItem(num);
   var checkedLi = document.getElementById("li-"+num);
   checkedLi.style.textDecoration = "line-through";
}); 

2 个答案:

答案 0 :(得分:2)

由于jQuery JavaScript,因此不需要 jQuery。窗口加载时,请在列表中单击,而不是复选框。在事件监听器的回调函数中,检查复选框是否为目标,然后获取此特定<div class='container'> <div class='slider'> <h1>I will Slide</h1> <p>My content</p> <p>My content</p> <p>My content</p> </div> </div>元素并应用您的CSS。

li

由于复选框是//get list and listen for click on your list const list = document.getElementById("list"); list.addEventListener("click", function(event) { const target = event.target; //ignore clicks on anything but checkbox if(target.type !== "checkbox") return; //apply css here target.parentNode.style.textDecoration = "line-through"; }); 的子项,而lili的子项,因此点击事件会从ul元素冒泡到您的列表,这种解决方案可行

在评论中进行对话后编辑:很高兴我们开始理解。

答案 1 :(得分:0)

在使用复选框等交互式元素时,您不需要JavaScript来控制元素的样式。

使用:

1)伪元素 ::after

2) Adjacent Sibling Combinator

3)伪类:checked

4)[for] attribute

允许我们控制表单控件之类的交互元素。复选框行为类似于OP:

  • 检查并通过直通检查

  • Font-Awesome图标作为奖励

  • 不涉及JavaScript。

尽管CSS解决方案适用于TODO列表,但它并不像JavaScript那样通用。在将来,您需要处理除表单控件之外的元素的事件处理,因此我添加了一个测试函数来演示Event Delegation

在CSS中注意:选择器的加倍是强制执行强specificity。我倾向于在处理Bootstrap时这样做,因为Bootstrap的样式表很难被覆盖。

在演示中评论的详细信息

演示

&#13;
&#13;
/* HTMLFormControlsCollection API makes forms easier to access*/
var idx = 0;
var lst = document.getElementById('lst');
var fX = document.forms.frm;
var xF = fX.elements;
var btn = xF.btn;
var txt = xF.txt;

btn.addEventListener('click', addTask, false);

/* This function uses Template Literals instead of literal string
|| and insertAdjacentHTML() method.
*/
function addTask(e) {
  idx++;
  var text = txt.value;
  var item = `<li id="li${idx}"class='item'>
                <input id="chx${idx}" class='chk' type="checkbox">
                <label for="chx${idx}" class='fa'>${text}</label>
              </li>`;
  text.value = "";
  lst.insertAdjacentHTML("beforeend", item);
}


/* This is to demonstrate Event Delegation 
|| The form listens for an event for itself and its children.
|| The Event Object property Event.currentTarget is the form.
|| Event.target is the origin of event (ex. clicked button).
|| e.target can be any of form's children so by using 
|| conditions (if, if else etc), and Event Object properties
|| we can delegate event handling for an unknown amount of
|| elements with just one parent/ancestor element.

ADD/DEL last slash on next line to toggle eventListeners 
/*/
fX.addEventListener('click', testEvent);
/*/
document.addEventListener('click', testEvent);
//*/

function testEvent(e) {
  if (e.target !== e.currentTarget) {
    console.log(e.target.tagName + ' ' + e.type);
  }
}
&#13;
:root {
  --r: 'Righteous', cursive;
  margin: 0;
  padding: 0;
  border: 0
}

body {
  /*background-image: url("http://pctechtips.org/apps/conf/img/Chicago-Wallpaper-3.jpg");*/
  min-height: 100vh;
  z-index: -10;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  color: white;
  font-size: 1.3rem;
}

.hero {
  min-height: auto;
  min-width: 100vw;
  background-color: rgba(31, 34, 118, 0.5);
}

h1 {
  margin-top: 12rem;
  margin-bottom: 0px;
  padding-bottom: 0px;
  font-family: var(--r);
}

.lead {
  font-size: 1.5rem;
  font-family: var(--r);
}

#frm hr {
  margin: 0;
  outline: 1px solid white;
}

ul {
  margin-top: 2rem;
  list-style: none;
}

li {
  border-bottom: 1px solid white;
  height: 32px;
  padding-top: 5px
}

#frm input,
#frm label {
  font: 400 1.2rem/1.4 Quicksand;
}
/* Using 1) pseudo-element ::after,  2) Adjacent Sibling
|| Combinator, 3) pseudo-class :checked, and 4) the [for]
|| attribute allows us to control interactive elements like form || controls. Checkbox behavior is like OP: checked and 
|| line-through check and Font-Awesome icons as a bonus involved
|| no JavaScript.
*/
/* Note: the doubling of selectors is to enforce strong
|| specificity. I tend to do this when dealing with Bootstrap
|| because Bootstrap's stylesheets are very difficult to 
|| override.
*/
.chk.chk {
  display: none;
}

.fa.fa {
  font: inherit;
  background-color: #e9ecef;
  border: 1px solid #e9ecef;
  padding: 0 0 0 5px;
  border-radius: 3px;
}

.fa.fa::after {
  float: right;
  content: "\f096";
  font: 400 24px/1 FontAwesome;
  width: 24px;
  height: 24px;
  margin: 0 0 0 5px;
}

.chk.chk:checked+.fa.fa {
  text-decoration: line-through;
}

.chk.chk:checked+.fa.fa::after {
  content: "\f046"
}

/* For demo only */
.as-console-wrapper {
  width: 45%;
  margin-left: 55%;
  max-height: 32px !important
}

.as-console-row {font-size:0;}
&#13;
<!DOCTYPE html>
<html>

<head>
  <title>TodoList App</title>
  <!-- bootstrap cdn -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <!-- google fonts -->
  <link href="https://fonts.googleapis.com/css?family=Quicksand|Righteous" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>

<body>
  <div class="hero">
    <div class="container">
      <h1 class="display-2 text-center">TodoList</h1>
      <p class="lead text-center">Welcome to my todoList applications</p>
      <div class="row">
        <form id="frm" class="col-8 mx-auto">
          <div class="input-group">
            <input id="txt" class="form-control" placeholder="Enter todo list item" value="">

            <button id="btn" type="button" class="btn btn-primary">Submit</button>
          </div>
        </form>
      </div>
      <hr>
      <div class="row">
        <ul id="lst" class="list col-8 mx-auto">
        </ul>
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
</body>

</html>
&#13;
&#13;
&#13;