没有在嵌套的span元素上调用Click处理程序



我的布局使用bootstrap css。以下是html。

<form id="todoform">
 <div id="todo-1" class="row">
 <div  class="col-lg-6">
  <div class="input-group input-group-lg">
  <span class="input-group-addon" id="sizing-addon1"> <input type="checkbox" id="chk-1" aria-label="..."></span>
  <input type="text" id="comment-1" class="form-control" placeholder="what is the work" aria-describedby="sizing-addon1">
  <span id="remove-1" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>
  </div>
</div>
</div>

我试着写了一个函数,它将在单击span元素后被调用,id=remove-1。这两个函数都是在就绪回调中调用的
以下是我尝试的方式
1)通过直接给出id

$(document).ready(function(){
 $("#remove-1").click(function()
         {
            console.log("clicked on image");
         });
 });

2)通过使用"on"附加显式处理程序

$(document).ready(function(){
  $("body").on("click",".glyphicon-remove",function()
         {
             console.log("clicked on image");
         });
  });

两种方式都不起作用。我用的是铬49。

您的JavaScript是正确的,您只需要设置span的样式,使其具有单击区域,例如

.glyphicon-remove {
  background: red;
  height: 10px;
  width: 10px;
  display: block;
}

在没有任何样式的情况下,元素是隐藏的,因此JS无法绑定到它

当前绑定到元素的pointer-events属性设置为none,这导致无法识别单击(这来自Bootstrap中的.form-control-feedback类)。

此外,你的z-index有点低,当<input>元素聚焦时,会导致你的实际图标被隐藏。

尝试添加以下CSS样式,这将解决问题:

#remove-1 {
     z-index: 3;
     pointer-events: auto;
}

你也可以在这里看到它的一个例子。

最新更新