jquery使动态元素的父元素可单击

时间:2017-12-22 19:06:42

标签: jquery html css

我有一个跨越td。我可以使跨度可点击,但是我无法点击父级。

这适用于范围

$(document).on('click', '.glyphicon-question-sign', function(){
          alert("test");
}); 

我试图让这个为父母工作,但事实并非如此。

$(document).on('click', '.glyphicon-question-sign:parent', function(){
          alert("test");
});

这是动态创建的html。

<td><span class="glyphicon glyphicon-question-sign text-warning">
</span> Unavailable
</td>

2 个答案:

答案 0 :(得分:2)

您可以使用:has()选择器匹配包含特定类元素的td

$(document).on("click", "td:has(.glyphicon-question-sign)", function() {
  alert("test");
})
td {
  width: 100%;
  border: 5px solid #000;
}

span {
  display: block;
  height: 40px;
  width: 100px;
  background-color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <td>
    <span class="glyphicon glyphicon-question-sign text-warning"></span>
  </td>
</table>

答案 1 :(得分:1)

$("span").on("click", function() {
  $(this).parent("td").css("border-color", "yellow");
})
td {
  width: 100%;
  border: 5px solid #000;
}

span {
  display: block;
  height: 40px;
  width: 100px;
  background-color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <td>
    <span class="glyphicon glyphicon-question-sign text-warning"></span>
  </td>
</table>

我不确定我是否正确理解你。我会这样做