Run jQuery function onclick

前端 未结 4 512
梦如初夏
梦如初夏 2021-02-08 02:28

so i implemented a bit of jQuery that basically toggles content via a slider that was activated by an tag. now thinking about it id rather have the DIV th

4条回答
  •  攒了一身酷
    2021-02-08 02:32

    Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:

     
    ...

    However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:

     $(document).ready( function() {
         $('.some-class').on('click', slideonlyone('sms_box'));
         // OR //
         $('.some-class').click(slideonlyone('sms_box'));
     });
    

    Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').


    EDIT

    After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the div with a data-attribute like so:

    ...

    To access the element's data-attribute you can use the attr() method as in @fmsf's example, but the best practice is to use jQuery's data() method like so:

     function slideonlyone() {
         var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
         var target_id  = $(this).data('target'); // This would be 'sms_box'
         ...
     }
    

    Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.

提交回复
热议问题