如何将jQuery用于预定义事件?

时间:2021-11-10 00:41:28

Are there any standard rules for implementing predefined events in a jQuery plugin?

是否有任何标准规则在jQuery插件中实现预定义事件?

For example, the special case of Zebra Accordion plugin (a tiny accordion plugin for jQuery) or any other plugin defines some events like below:

例如,Zebra Accordion插件(jQuery的一个小型手风琴插件)或任何其他插件的特殊情况定义了一些事件,如下所示:

Zebra Accordion Events:

Zebra手风琴活动:

onClose: Event fired after a tab is collapsed.

onClose:折叠选项卡后触发的事件。

onOpen: Event fired after a tab is collapsed.

onOpen:折叠选项卡后触发的事件。

In this case if I wanted to add a div with special Font Awesome characters (such as fa-chevron-down) after the box title when collapsed (Closed, collapsed state) and remove that character and replace it with a new character (like fa-chevron-up) near the box title when expended(opened state). I would like to finally add some functionality like jQuery Accordion to it. I've tried with the below code but it appears something is wrong:

在这种情况下,如果我想在折叠后的方框标题(封闭,折叠状态)之后添加一个带有特殊Font Awesome字符(例如fa-chevron-down)的div,并删除该字符并将其替换为新字符(如fa -chevron-up)在支出标题附近(开放状态)。我想最后添加一些像jQuery Accordion这样的功能。我已尝试使用以下代码,但似乎出现了问题:

$('.Zebra_Accordion').on('onOpen', function(e) {
      $(this).append( "<span class='fa fa-chevron-down'></span>" );
  });

$('.Zebra_Accordion').off('onClose', function(e) {
      $(this).append( "<span class='fa fa-chevron-up'></span>" );
  });

3 个解决方案

#1


9  

Most jQuery plugins have an options object that you pass in. In here you can define the properties you want to set including event handlers.

大多数jQuery插件都有一个传入的选项对象。在这里,您可以定义要设置的属性,包括事件处理程序。

The documentation for the zebra accordion events says for each of the events the plugin provides:

斑马手风琴活动的文档说明插件提供的每个事件:

The callback function takes 3 arguments:

回调函数有3个参数:

  • the tab's position in the accordion (0 based)
  • 标签在手风琴中的位置(基于0)

  • the associated title element, as a jQuery object
  • 关联的title元素,作为jQuery对象

  • the tab, as a jQuery object
  • 选项卡,作为jQuery对象

I've just given them 3 suitable names, and used the second argument (which I arbitrarily named hdr).

我刚给他们3个合适的名字,并使用了第二个参数(我任意命名为hdr)。

As noted in the documentation the hdr argument returned is a jQuery object wrapping the <dt> element (at least in my example). On this object I called the jQuery function .find() to find the element(s) inside that <dt> having the fa-chevron-* class, and then I switch the classes on that span by chaining further jQuery functions.

如文档中所述,返回的hdr参数是一个包装

元素的jQuery对象(至少在我的示例中)。在这个对象上,我调用了jQuery函数.find()来查找具有fa-chevron- *类的
中的元素,然后通过链接更多jQuery函数来切换该span上的类。

As noted in the comments you can do it perfectly well in-line like:

如评论中所述,您可以完美地在线完成,例如:

var accordian = new $.Zebra_Accordion($('.Zebra_Accordion'), {
    collapsible: true,
    onBeforeOpen: function(index, hdr, body) {
       hdr.find(".fa-chevron-down").removeClass('fa-chevron-down').addClass('fa-chevron-up');
    },
    onBeforeClose: function(index, hdr, body) {
       hdr.find(".fa-chevron-up").removeClass('fa-chevron-down').addClass('fa-chevron-down');
    }
});

And in this particular case I would, but I wanted to illustrate what to do when the handlers have more code, in which case making them separate functions makes for better readability.

在这种特殊情况下我会这样做,但我想说明当处理程序有更多代码时要做什么,在这种情况下,使它们成为单独的函数可以提高可读性。

Don't forget to use console.log() a lot - it is a JavaScript developer's best friend.

不要忘记使用console.log()很多 - 它是JavaScript开发人员最好的朋友。

To check what this Zebra Accordion was providing me I did the following first:

为了检查这部Zebra手风琴为我提供了什么,我先做了以下几点:

onBeforeOpen: function(index, hdr, body) {
       console.log("onBeforeOpen", index, hdr, body);
},

This output shows up in the browser's developer's console.

此输出显示在浏览器的开发人员控制台中。

Here's my demo putting it all together:

这是我的演示将它们放在一起:

$(function() {
  
  // add default chevrons here so they only get appended once
  $(".Zebra_Accordion dt").append("<span class='chevron fa fa-chevron-down'></span>");

  // set up the according options
  var accordian = new $.Zebra_Accordion($('.Zebra_Accordion'), {
    collapsible: true,
    onBeforeOpen: showCollapseChevron,
    onBeforeClose: showExpandChevron
  });
  
  function showExpandChevron(index, hdr, body) {
      hdr.find(".fa-chevron-up").removeClass('fa-chevron-up').addClass('fa-chevron-down');
  }
  
  function showCollapseChevron(index, hdr, body) {
      hdr.find(".fa-chevron-down").removeClass('fa-chevron-down').addClass('fa-chevron-up');
  }
  
});
dl.Zebra_Accordion { width: 100% }
dl.Zebra_Accordion dt { background: #000; color: #FFF; font-weight: bold; padding: 5px }
dl.Zebra_Accordion dd { background: #EFEFEF; padding: 15px; margin: 1px 0 } 
dl.Zebra_Accordion dt.Zebra_Accordion_Expanded { background: #C40000 }

.chevron {
  margin-left: 5px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/stefangabos/Zebra_Accordion/dist/zebra_accordion.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/stefangabos/Zebra_Accordion/dist/zebra_accordion.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<dl class="Zebra_Accordion">
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
</dl>

External Demo https://jsfiddle.net/8wzvucgb/

外部演示https://jsfiddle.net/8wzvucgb/

#2


3  

The "Plugin Events" aren't really events, and won't work with on().

“插件事件”不是真正的事件,也不适用于on()。

You can supply callbacks in the invocation that will be called when the accordion opens and closes.

您可以在手风琴打开和关闭时调用的调用中提供回调。

Their "events" are coded in the initial invocation of the plugin:

他们的“事件”在插件的初始调用中编码:

var myAccordion = new $.Zebra_Accordion($('.Zebra_Accordion'),{
      onOpen:function(index,$title,$block){…},
      onClose:function(index,$title,$block){…}
});

It's an old-fashioned way of doing things. It's much more flexible of plugins use real events.

这是一种老式的做事方式。插件使用真实事件的灵活性要高得多。

#3


0  

What you might need: watch out for dynamically created html. For example

你可能需要什么:注意动态创建的html。例如

<script>
...
$('#add').click(function() {
  $('#container').append('<div class="item"> new item </div>')
})
$('#container .item').on('click', function() { ... })
...
</script>  
<input id="add" value="Add 1 item" type="button"/>  
<div id="container">
  <div class="item"> click item 1 </div>
  <div class="item"> click item 2 </div>
</div>

The problem is that the dynamically added items will not respond to the click event, because the html didn't exist yet.

问题是动态添加的项不会响应click事件,因为html还不存在。


What you do, is this:

你做的是这样的:

$('#container').on('click', '.item', function() { ... })

Then, jQuery will listen to a click on #container, and then at click time it will dynamically search the .item children.

然后,jQuery将听取#container的点击,然后在点击时它会动态搜索.item孩子。

#1


9  

Most jQuery plugins have an options object that you pass in. In here you can define the properties you want to set including event handlers.

大多数jQuery插件都有一个传入的选项对象。在这里,您可以定义要设置的属性,包括事件处理程序。

The documentation for the zebra accordion events says for each of the events the plugin provides:

斑马手风琴活动的文档说明插件提供的每个事件:

The callback function takes 3 arguments:

回调函数有3个参数:

  • the tab's position in the accordion (0 based)
  • 标签在手风琴中的位置(基于0)

  • the associated title element, as a jQuery object
  • 关联的title元素,作为jQuery对象

  • the tab, as a jQuery object
  • 选项卡,作为jQuery对象

I've just given them 3 suitable names, and used the second argument (which I arbitrarily named hdr).

我刚给他们3个合适的名字,并使用了第二个参数(我任意命名为hdr)。

As noted in the documentation the hdr argument returned is a jQuery object wrapping the <dt> element (at least in my example). On this object I called the jQuery function .find() to find the element(s) inside that <dt> having the fa-chevron-* class, and then I switch the classes on that span by chaining further jQuery functions.

如文档中所述,返回的hdr参数是一个包装

元素的jQuery对象(至少在我的示例中)。在这个对象上,我调用了jQuery函数.find()来查找具有fa-chevron- *类的
中的元素,然后通过链接更多jQuery函数来切换该span上的类。

As noted in the comments you can do it perfectly well in-line like:

如评论中所述,您可以完美地在线完成,例如:

var accordian = new $.Zebra_Accordion($('.Zebra_Accordion'), {
    collapsible: true,
    onBeforeOpen: function(index, hdr, body) {
       hdr.find(".fa-chevron-down").removeClass('fa-chevron-down').addClass('fa-chevron-up');
    },
    onBeforeClose: function(index, hdr, body) {
       hdr.find(".fa-chevron-up").removeClass('fa-chevron-down').addClass('fa-chevron-down');
    }
});

And in this particular case I would, but I wanted to illustrate what to do when the handlers have more code, in which case making them separate functions makes for better readability.

在这种特殊情况下我会这样做,但我想说明当处理程序有更多代码时要做什么,在这种情况下,使它们成为单独的函数可以提高可读性。

Don't forget to use console.log() a lot - it is a JavaScript developer's best friend.

不要忘记使用console.log()很多 - 它是JavaScript开发人员最好的朋友。

To check what this Zebra Accordion was providing me I did the following first:

为了检查这部Zebra手风琴为我提供了什么,我先做了以下几点:

onBeforeOpen: function(index, hdr, body) {
       console.log("onBeforeOpen", index, hdr, body);
},

This output shows up in the browser's developer's console.

此输出显示在浏览器的开发人员控制台中。

Here's my demo putting it all together:

这是我的演示将它们放在一起:

$(function() {
  
  // add default chevrons here so they only get appended once
  $(".Zebra_Accordion dt").append("<span class='chevron fa fa-chevron-down'></span>");

  // set up the according options
  var accordian = new $.Zebra_Accordion($('.Zebra_Accordion'), {
    collapsible: true,
    onBeforeOpen: showCollapseChevron,
    onBeforeClose: showExpandChevron
  });
  
  function showExpandChevron(index, hdr, body) {
      hdr.find(".fa-chevron-up").removeClass('fa-chevron-up').addClass('fa-chevron-down');
  }
  
  function showCollapseChevron(index, hdr, body) {
      hdr.find(".fa-chevron-down").removeClass('fa-chevron-down').addClass('fa-chevron-up');
  }
  
});
dl.Zebra_Accordion { width: 100% }
dl.Zebra_Accordion dt { background: #000; color: #FFF; font-weight: bold; padding: 5px }
dl.Zebra_Accordion dd { background: #EFEFEF; padding: 15px; margin: 1px 0 } 
dl.Zebra_Accordion dt.Zebra_Accordion_Expanded { background: #C40000 }

.chevron {
  margin-left: 5px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/stefangabos/Zebra_Accordion/dist/zebra_accordion.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/stefangabos/Zebra_Accordion/dist/zebra_accordion.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<dl class="Zebra_Accordion">
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
  <dt>Lorem ipsum dolor sit amet consectetuer</dt>
  <dd>
    Lorem ipsum dolor sit amet consectetuer facilisis lacinia sapien ac et. Quis hendrerit neque congue pretium iaculis justo laoreet orci elit condimentum. Eros natoque Curabitur accumsan eget quis porttitor Sed Vestibulum amet sed.
  </dd>
</dl>

External Demo https://jsfiddle.net/8wzvucgb/

外部演示https://jsfiddle.net/8wzvucgb/

#2


3  

The "Plugin Events" aren't really events, and won't work with on().

“插件事件”不是真正的事件,也不适用于on()。

You can supply callbacks in the invocation that will be called when the accordion opens and closes.

您可以在手风琴打开和关闭时调用的调用中提供回调。

Their "events" are coded in the initial invocation of the plugin:

他们的“事件”在插件的初始调用中编码:

var myAccordion = new $.Zebra_Accordion($('.Zebra_Accordion'),{
      onOpen:function(index,$title,$block){…},
      onClose:function(index,$title,$block){…}
});

It's an old-fashioned way of doing things. It's much more flexible of plugins use real events.

这是一种老式的做事方式。插件使用真实事件的灵活性要高得多。

#3


0  

What you might need: watch out for dynamically created html. For example

你可能需要什么:注意动态创建的html。例如

<script>
...
$('#add').click(function() {
  $('#container').append('<div class="item"> new item </div>')
})
$('#container .item').on('click', function() { ... })
...
</script>  
<input id="add" value="Add 1 item" type="button"/>  
<div id="container">
  <div class="item"> click item 1 </div>
  <div class="item"> click item 2 </div>
</div>

The problem is that the dynamically added items will not respond to the click event, because the html didn't exist yet.

问题是动态添加的项不会响应click事件,因为html还不存在。


What you do, is this:

你做的是这样的:

$('#container').on('click', '.item', function() { ... })

Then, jQuery will listen to a click on #container, and then at click time it will dynamically search the .item children.

然后,jQuery将听取#container的点击,然后在点击时它会动态搜索.item孩子。