【问题标题】:Select only the child of an element, identified by his class仅选择由其类标识的元素的子元素
【发布时间】:2019-01-03 05:55:43
【问题描述】:

如何仅在我单击的元素的子元素(由其类标识)上激活单击事件?

我尝试了这个,但似乎激活了页面上 .a-collaps-button 的所有 onclick 事件(我有多个 .collaps-button 和多个 .a-collaps-button

<button class="collaps-button">
  <a href="#adminModal" class="a-collaps-button" data-toggle="modal" onclick="showModalContentjs('modificy')">Modificy</a>
</button>
$('.collaps-button').click(function () {
  $(this).children('.a-collaps-button').click();
});

对于 CSS,我这样做并且它有效

$(function () {
  $('.collaps-button').hover(function () {
    $(this).children('.a-collaps-button').css('color', '#f44242');
    $(this).children('.a-collaps-button').css('text-decoration', 'none');
  }, function () {
    $(this).children('.a-collaps-button').css('color', 'white');
    $(this).children('.a-collaps-button').css('text-decoration', 'none');
  });
});

【问题讨论】:

  • 为什么要使用 js 来设置悬停 css 样式?另外我不认为按钮内的锚是有效的
  • @Pete 我将重新打开它,因为虽然该副本与 OPs 问题相匹配,但其 HTML 中存在巨大缺陷,这使得问题的意义没有实际意义。

标签: javascript jquery html css


【解决方案1】:

您的主要问题是您的 HTML 无效。您不能嵌套可点击元素,即。您不能将a 元素放在button 中。

要解决此问题,请删除 a 元素,然后只需将单击该 a 时执行的任何逻辑附加到 button 的单击事件即可。另请注意,您不应使用过时的on* 事件属性。使用不显眼的事件处理程序,例如 addEventListener() 或 jQuery 的 on() 或事件快捷方式,例如 click()

另外请注意,您不应该使用 JS 来修改 UI。您的 hover 逻辑更适合 CSS。试试这个:

$('.collaps-button').click(function() {
  showModalContentjs('modificy');
});

function showModalContentjs(foo) {
  console.log(foo);
}
.collaps-button {
  color: white;
  text-decoration: none
}
.collaps-button:hover {
  color: #f44242;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="collaps-button">Modificy</button>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
相关资源
最近更新 更多