【问题标题】:Unable to trigger an evt when clicking on a specific button单击特定按钮时无法触发 evt
【发布时间】:2019-07-25 14:35:07
【问题描述】:

我在三个单独的表(使用 DataTables 构建)旁边有三个加号 (+) 按钮。由于 +s 是在一个位置(使用 DT)创建的,因此单击其中任何一个都会打开相同的模式。在大多数情况下,它们具有相同的 DOM 结构和类。

我想让它点击一个 +s 做一件事,点击第二个 + 做另一件事,等等。父母的一些 ID 略有不同,我正在尝试使用特异性来定位特定的 +s。

我之所以写,是因为我无法仅定位一个 +(console.log 不起作用)。

这可能是一件很愚蠢的事情,但我一直在修补这个并且没有任何运气,所以我想在这里问一下。

JS sn-p:

// $(document).on("click", ".btn-new", disp._newRole); // ----- this works, but it triggers every +

$(document).on("click", "#DataTables_Table_2_wrapper > .btn-group > .btn-default > .btn-new", disp._newRole);

$(document).on("click", "#DataTables_Table_2_wrapper > .btn-group > .btn-default > .btn-new", function() {
    console.log('hello')
});

屏幕截图:

#DataTables_Table_2_wrapper 是独一无二的。另外两个表使用 0 和 1 而不是 2。

JS(创建 + 的地方)

buttons: [
                {
                  text:      '<div class="btn btn-new" style="bottom:0.75rem; padding-right:2rem; position:relative;" title="Click to add new search"><i class="fa fa-plus"></i></div>',
                  titleAttr: 'Add',
                  exportOptions: {
                      columns: _colExport
                  }
                },

【问题讨论】:

  • HTML代码请提供sn-p
  • 将 html 作为代码而不是图像提供会非常好
  • @Rishab 刚刚添加了
  • 不,你必须添加渲染的html,这是在图像上提供的

标签: javascript jquery events datatables target


【解决方案1】:

你错过了目标中的一个孩子.btn-new

$(document).on("click", "#DataTables_Table_2_wrapper > .btn-group > .btn-default > span > .btn-new > .fa-plus", function() {
console.log('hello')});

我建议你声明一个自定义类并避免过于嵌套的目标,因为它很容易产生错误并降低代码的可读性。

【讨论】:

  • 嘿@andrea-facchini,感谢您提供的信息。但不幸的是,该事件没有被触发。 $(document).on("click", ".btn-new", disp._newRole); 这仍然有效(刚刚测试过),所以我不确定为什么其他两行不起作用。
  • @Bodrov 我编辑了我的答案,我缺少一个 span 元素
  • @andrea-facchnini 做到了,谢谢!我肯定会合并一个自定义类,让事情更容易阅读(和使用)。
【解决方案2】:

如果您确定包装器仅包含符合您的条件的 1 个元素,我建议您使用 :first-of-type 选择器或不使用它来简化选择器。这里我准备了一个示例。

$(document).on('click', '#a1 .your-class:first-of-type', function(){
	console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a1">
	<div>
		<i class='your-class'>1</i>
	</div>
</div>
<div id="a2">
<div>
		<i class='your-class'>2</i>
	</div>
</div>

如果您无法使其适应当前的代码,我会帮助您。

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多