在JavaScript中连接函数

时间:2015-06-17 09:31:31

标签: javascript jquery

我有以下两个JavaScript函数:

JS 1

$( ".show-more" ).click(function() {
  event.preventDefault();
  $( this ).next().slideToggle( "fast", function() {
  });
  $( this ).toggleClass("show-more-rotate");
});

JS 2

$( ".show-more-section" ).click(function() {
  event.preventDefault();
  $( this ).next().slideToggle( "fast", function() {
  });
  $( this ).toggleClass("show-more-section-rotate");
});

有没有办法将两个函数连接成一个?我尝试了以下方法,但功能似乎只适用于最后列出的元素:

JS - 连接失败的尝试

$( ".show-more, .show-more-section" ).click(function() {
  event.preventDefault();
  $( this ).next().slideToggle( "fast", function() {
  });
  $( this ).toggleClass("show-more-rotate, show-more-section-rotate");
});

4 个答案:

答案 0 :(得分:2)

见内联评论:

// bind event on both the elements
$(".show-more, .show-more-section").on('click', function (event) {
//                                                        ^^^^^^ Add this
    event.preventDefault();

    $(this).next().slideToggle("fast", function () {});
    $(this).toggleClass("show-more-rotate show-more-section-rotate");
    // Remove `,` from toggleClass
});

修改

您还可以将方法链接为:

$(this).toggleClass("show-more-rotate show-more-section-rotate")
    .next().slideToggle("fast", function () {});

<强>更新

如果要在完成slideToggle之后切换类:

var $this = $(this);
$this.next().slideToggle("fast", function () {
    $this.toggleClass("show-more-rotate show-more-section-rotate")
});

答案 1 :(得分:1)

您可以创建处理程序函数,并可以在单击处理程序

中重复使用它
$( ".show-more" ).click(showMoreClickHandler);

$( ".show-more-section" ).click(showMoreClickHandler);

function showMoreClickHandler(e) {
    e.preventDefault();
    $( this ).next().slideToggle( "fast", function() {});
    $( this ).toggleClass("");
}

对于切换类,您可以在HTML中添加data-toggle-class属性,并可以读取值并执行切换。

我希望,show-more-rotateshow-more-section-rotate应该应用于它的相应元素而不是另一个元素。

答案 2 :(得分:1)

试试这个: -

SELECT *
INTO Foo
FROM
    (
        SELECT DISTINCT LastName 
        FROM Clients 
        WHERE LastName LIKE 'D*'
    UNION ALL
        SELECT DISTINCT LastName 
        FROM Clients 
        WHERE LastName LIKE 'T*'
    )

Demo

答案 3 :(得分:0)

删除toggleClass中的逗号:

$(".show-more, .show-more-section").on('click', function (event) {
    event.preventDefault();
    $(this).next().slideToggle("fast", function () {
    });
    $(this).toggleClass("show-more-rotate show-more-section-rotate");
});