最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery trigger event on element with id to run handler defined by class in an included twig template - Stack Overfl

programmeradmin0浏览0评论

When calling jQuery's trigger function by the id selector, is it possible to trigger the event handler for that element that is defined by the same element's class selector? For example, say I have this HTML:

<div class="my_button" id="my_button_1"></div>

And this jQuery

$('.my_button').click(function() { 
    alert("button was clicked")
});

I'm looking call $('#my_button_1').trigger('click') ... and have it trigger the above jQuery for that element in the cleanest way possible. Any help is appreciated.

EDIT: Based on the ments below, it's clearly not an issue with jQuery. Here's the actual code being used.

{% block javascripts %}
    {{ include('MyMainBundle:Event:wizard.js.twig') }}
{% endblock %}

Handler defined in wizard.js:

    $('.event_type_option').click(function() {

        alert('option clicked');
        Event.eventTypeId = $(this).attr('id').substring(11);
        customComboSelect(this, $('#event_type_text'));
    });

    $('.people_range_option').click(function() {

        alert('range clicked');
        Event.peopleRangeId = $(this).attr('id').substring(13);
        customComboSelect(this, $('#people_range_text'));
    });

Trying to trigger the event below this:

{% if event is defined %}
    <script>
        $(document).ready(function() {

            $('#event_type_{{ event.eventType.id }}').trigger('click');
            $('#people_range_{{ event.peopleRange.id }}').trigger('click');
        });
    </script>
{% endif %}

Additionally, The events are successfully triggered if I try triggering them directly following the handler definitions.

When calling jQuery's trigger function by the id selector, is it possible to trigger the event handler for that element that is defined by the same element's class selector? For example, say I have this HTML:

<div class="my_button" id="my_button_1"></div>

And this jQuery

$('.my_button').click(function() { 
    alert("button was clicked")
});

I'm looking call $('#my_button_1').trigger('click') ... and have it trigger the above jQuery for that element in the cleanest way possible. Any help is appreciated.

EDIT: Based on the ments below, it's clearly not an issue with jQuery. Here's the actual code being used.

{% block javascripts %}
    {{ include('MyMainBundle:Event:wizard.js.twig') }}
{% endblock %}

Handler defined in wizard.js:

    $('.event_type_option').click(function() {

        alert('option clicked');
        Event.eventTypeId = $(this).attr('id').substring(11);
        customComboSelect(this, $('#event_type_text'));
    });

    $('.people_range_option').click(function() {

        alert('range clicked');
        Event.peopleRangeId = $(this).attr('id').substring(13);
        customComboSelect(this, $('#people_range_text'));
    });

Trying to trigger the event below this:

{% if event is defined %}
    <script>
        $(document).ready(function() {

            $('#event_type_{{ event.eventType.id }}').trigger('click');
            $('#people_range_{{ event.peopleRange.id }}').trigger('click');
        });
    </script>
{% endif %}

Additionally, The events are successfully triggered if I try triggering them directly following the handler definitions.

Share Improve this question edited Apr 19, 2013 at 16:34 RHarrington asked Apr 19, 2013 at 16:08 RHarringtonRHarrington 1,0491 gold badge9 silver badges12 bronze badges 17
  • Is your click handler inside of $(document).ready? – Ian Commented Apr 19, 2013 at 16:09
  • 1 Why don't you simply try it and see what happens? – j08691 Commented Apr 19, 2013 at 16:11
  • You have a syntax error. )}; should be }); – Ian Commented Apr 19, 2013 at 16:12
  • And yes, it works just fine because the selectors don't matter with what you're concerned about. If the click event was bound to an element, it doesn't matter how you select it - you can trigger the event. Here - jsfiddle/yV57x – Ian Commented Apr 19, 2013 at 16:14
  • 1 @RHarrington Technically, yes. The $(document).ready handler that binds the events needs to happen first. It would be helpful to have more of your code available – Ian Commented Apr 19, 2013 at 16:29
 |  Show 12 more ments

4 Answers 4

Reset to default 2

Event binding in jQuery is done as a "First In, First Out" queue (it's a little more plicated with delegated events and namespaced events, but that's not too important now).

Meaning, as events are bound to an element, they are later executed in the same order when the event is triggered.

In your case, you need to bind the click event handler before attempting to .trigger() it. Since the event binding and the triggering are in different $(document).ready handlers, the handler that binds the events needs to execute before the handler that triggers the event.

Here's an example of what happens when you try to trigger before binding: http://jsfiddle/yV57x/1/ - notice how no alert occurs (unless you actually click the element in the HTML). Flipping around the $(document).ready handler bindings fixes the problem.

And just as a note, your original intent is perfectly valid. If the click event was bound to an element, it doesn't matter how you select it - you can trigger the event as long as you can get it. Test it here: http://jsfiddle/yV57x/

Yes, possible. As

$('#my_button_1') and $('.my_button') both point's to the same element

$('.my_button').click(function() { 
    alert("button was clicked")
});
$('#my_button_1').trigger('click');

Is the content on the page when you are binding the event? The document could be ready, but if you are loading dynamic content or creating content and appending it on the fly on the page, the elements may not be present when the event is trying to be bound.

My guess, based on the minimal information you've provided, is that the above is true in which case you need to create a delegated event like the following:

For jQuery 1.7 or Higher:
.on() Documentation

$(document).on('click', '.my_button', function () {
    alert("Button was clicked!");
});

For jQuery 1.4.2 - 1.7:
.delegate() Documentation

$(document).delegate('.my_button', 'click', function () {
    alert("Button was clicked!");
});

For jQuery 1.3 - 1.4.2:
.live() Documentation

$('.my_button').live('click', function () {
    alert("Button was clicked!");
});

These methods use event delegation. The element(s) do not even have to be on the page when these handlers are setup. As the content is dynamically loaded, jQuery will attach the event handlers for you automatically.

In addition it should be noted that if content, which has a handler is removed from the DOM, you should use the .remove() or .empty() jQuery mands to prevent memory leaks as these first remove all bound events and then the elements.

Edit
I added reference links to all the appropriate documentation for each call. Also the last call was supposed to be .live() not .on(). That was a copy and paste error but is now fixed.

Hope this helps.

Yes, this is how it works.

The selector part selects elements $('.my_button'). Those elements get assigned an onclick handler:

.click(function() { 
    alert("button was clicked")
)};

Then $('#my_button_1').trigger('click') should give you an alert.


The 'cleanest' way to call event handler programmatically is (in my opinion) to not use trigger. The DOM is view, treat it as a view. If you're going to do things in your controller keep them in the controller.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论