多个JQuery单击功能

时间:2015-07-12 09:53:05

标签: javascript jquery function onclick click

我们说我希望得到以下div中的10-20个。如何将jQuery代码合并为一位,以便我不必复制它?

<div class="one">
    <h2>Test</h2>
</div>

<div class="one_new">
    <h2>Test</h2>
</div>

<div class="two">
    <h2>Test</h2>
</div>

<div class="two_new">
    <h2>Test</h2>
</div>

$(function() {
    $('.one').click(function() {
    $('.one').css( "display", "none")
    $('.one_new').css( "display", "table");
  });
});

$(function() {
    $('.two').click(function() {
    $('.two').css( "display", "none")
    $('.two_new').css( "display", "table");
  });
});

更新:https://jsfiddle.net/d9x45nyd/12/

3 个答案:

答案 0 :(得分:1)

您要解决的基本问题是如何关联元素(在您的情况下为div),以便在单击一个元素时,显示相关元素并隐藏原始元素。

有很多方法可以做到这一点:

  • 基于层次结构(即找到下一个div)
  • 选择器数组(难以用HTML维护)
  • 每个项目一个处理程序(您的原始文件,但不能很好地扩展)

在大多数情况下,我的个人建议是“数据驱动”&#34; HTML。也就是说,HTML被编写为包含足够的元数据以允许通过相对简单的代码做出决定。这样可以进行所有维护,例如对于新元素,以及元素本身。

数据驱动的一种简单方法是在元素上使用data-属性,例如保持选择器的相关元素。

e.g。这是一个解释性的例子(因此不是所需的最小代码):

HTML:

<div class="one" data-target=".one_new">
     <h2>Test one</h2>
</div>
<div class="one_new" style="display:none;">
     <h2>Test one new</h2>
</div>
<div class="two" data-target=".two_new">
     <h2>Test two</h2>
</div>
<div class="two_new" style="display:none;">
     <h2>Test two new</h2>
</div>

的jQuery

$(document).on('click', 'div', function () {
    // Only bother to wrap this once - common practice
    var $this = $(this);
    // Get the data-target element from the div clicked
    var target = $this.data('target');
    // If it has a target...
    if (target) {
        // use it as a jQuery selector to select the matching div 
        $(target).css('display', 'table');
        $this.hide();
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/mkLqvrrm/2/

此方法使用单个委托事件处理程序,附加到不变的祖先元素。如果没有其他更接近/方便的话,document是最好的默认值。它的工作原理是通过监听事件(即click)来冒泡到祖先。它然后只将jQuery选择器应用于bubble bubble中的元素。它然后仅将函数应用于导致事件的匹配元素。

此方法连接效率非常高,并且在事件发生时,运行时开销可以忽略不计(因为您可以快速单击鼠标以注意与直接连接的事件处理程序相比的任何差异)。

答案 1 :(得分:0)

您可以尝试以下代码:

&#13;
&#13;
$(function() {
    $('div').click(function() {
    var classAttr = $(this).attr('class');
    $('.'+classAttr).css( "display", "none")
    $('.'+classAttr +'_new').css( "display", "table");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">
    <h2>Test</h2>
</div>

<div class="one_new"  style="display:none">
    <h2>Test one_new</h2>
</div>

<div class="two">
    <h2>Test</h2>
</div>

<div class="two_new" style="display:none">
    <h2>Test two_new</h2>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

创建一个以选择器作为参数的函数,并创建一个单击处理程序,如下所示:

function attachClickHandler(selector) {
    $(selector).click(function() {
        $(this).css('display', 'none');
        $(selector + '_new').css('display', 'table');
    });
}

var selectors = ['.one', '.two'];
for(var i = 0; i < selectors.length; i++) {
    attachClickHandler(selectors[i]);
}

此问题还有许多其他解决方案,但这是将所需jQuery功能分解的最简单示例。

相关问题