I'm an absolute noob with jQuery and pretty crap at frontend development so here's my question.
With the following HTML
<select id="event_category_id" name="event_category_id">
<option value="">Select Category</option>
<option value="1">Category One</option>
<option value="2">Category Two</option>
<option value="3">Category Three</option>
</select>
And the following jQuery
$(document).ready(function() {
// commands go here
$('#event_category_id option').click( function(e) {
// e.stopImmediatePropagation();
alert( $('#event_category_id option:selected').text() );
});
});
I get the alert being displayed twice, with the correct text of the selection each time, for one click. It's rectified by un-commenting the stopImmediatePropagation.
So my question is,if this is 开发者_开发知识库event bubbling/capturing, wouldn't one of the alerts be blank as the select doesn't have text, only the option.
Or am I on the wrong track with how I think all of this works works?
Thanks for your time.
don't use the click
event. Use the change
event instead.
$(document).ready(function() {
$('#event_category_id').change( function(e) {
alert( $(this).children('option:selected').text() );
});
});
Reference: change
try...
$('#event_category_id').change( function(e) {
alert( $(this).find(':selected').text() );
});
play with the demo
To try to explain bubbling of events as a broad topic.
The event object provides the .stopPropagation() method, which can halt the bubbling process completely for the event.this method is a plain JavaScript feature, but cannot be safely used across all browsers. But if all the event handlers are registered correctly using jQuery, you can use that method.
stopPropagation prevents any objects beyond the current from recieving the event, and this can be within any phase of the event. stopImmediatePropagation does the same but also takes the extra step of preventing additional events within the current target receiving the event from happening too.
Default Actions
When using elements that have default actions like which has a default action of redirecting on a click. Similarly, when the Enter key is pressed while the user is editing a form, the submit event is triggered on the form, but then the form submission actually occurs after this.
If these default actions are undesired, calling .stopPropagation() on the event will not help. These actions occur nowhere in the normal flow of event propagation. Instead, the .preventDefault() method will serve to stop the event in its tracks before the default action is triggered.
To stop both bubbling and default actions, i.e. to call the .stopPropogation() and the .preventDefault() methods, you simply return false
;
精彩评论