jQuery '#' + data("target") pattern

15

我经常看到这个:

<a href="#" id="trigger" data-target="content">Click me</a>
<div id="content">And something will happen here</div>

像这样的 JS 代码:

$("#trigger").click(function(){
  $("#" + $(this).data("target")).hide();
})

使用字符串拼接来创建选择器,然后再用它来获取目标元素,这种方式对我来说有点奇怪。在JavaScript(并且可以使用jQuery)中,有没有更好的模式可以在一个元素上设置处理程序,使其能够了解另一个目标元素?


2
这可能会感觉有点尴尬,但并没有什么问题。 - j08691
1
@j08691 我知道它可以工作,但我正在寻找一些有经验的意见,来自那些维护过更大型JS项目的人,以了解最佳实践。 - spike
6个回答

32

为什么要进行字符串拼接,只需使用#存储id即可。

<a href="#" id="trigger" data-target="#content">Click me</a>

$("#trigger").click(function(){
  $($(this).data("target")).hide();
})

同样,您可以将任何选择器存储为原样,例如data-target 中的 .tab1 等,这样您就不必在点击或任何事件内再次执行字符串连接。


1
只是出于好奇,$(this).data("target") 周围的 $() 是否真的必要? - SirDerpington
4
是的,this是一个DOM元素,没有data函数。data是jquery的一个函数,所以你必须使用 $ 来创建一个jquery对象。 - James Montagne
1
这种方法的另一个好处是,我不再局限于使用id。任何选择器都可以使用。 - spike

4
您可以简单地使用。
$('#content').modal('toggle');

在你的代码任何地方启动模态框的显示和隐藏,你可以直接使用“show”/“hide”功能。我假设你正在使用Bootstrap和最新版本的jQuery。祝你使用愉快!

1
这并不回答我的问题。问题不是关于如何使用JS隐藏或显示东西,而是关于在HTML中嵌入动态选择器目标的模式。 - spike

3

我认为下面的方法会更好,为什么不试试:

// Set the target
$("#trigger").data('target', $('#content'));

// Get the target
$("#trigger").click(function(){
  $(this).data("target").hide();
})

如果你是从后端设置它,我建议像其他人建议的那样将哈希与属性值一起包含。

<a href="#" id="trigger" data-target="#content">Click me</a>

$("#trigger").click(function(){
     var target = $(this).data("target"); 
     $(target).hide();
})

每当我看到这样的操作时,数据属性都会被使用,因为它是从后端设置的。 - James Montagne
好的,我希望JS是通用的,这样我就可以在我的标记中指定目标,一切都会流畅进行。我想问题实际上是如何从HTML中的字符串转换为javascript中的对象。将data-target设置为实际的jquery对象是理想的,但如何通用地实现呢? - spike

1
你总是可以选择构建选择器,这看起来比在选择器内部连接字符串要好看一些。
$("#trigger").click(function(){
    var selector = "#" + $(this).data("target");
    $(selector).hide();
});

一点更好,不确定是否符合您的要求。

0

我会完全跳过数据,从而实现优雅降级。

<a href="#content" id="trigger" data-target="">Click me</a>
<div id="content">And something will happen here</div>

使用

$("#trigger").click(function(e){
  e.preventDefault();
  $( $(this).attr("href") ).show();
  // note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash
})

0

$(this).attr('data-target', '#myTarget');

这对我有用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接