Events…
Events auslösen
var the_event = 'some_event'; var the_element_id = 'some_id'; $(document).trigger(the_event, [ the_element_id, $('#' + the_element_id).val() ]);
HTML select
var the_event = 'some_event'; var the_element_id = 'some_id'; $('#' + the_element_id).change(function() { $(document).trigger(the_event, [ the_element_id, $('#' + the_element_id).val() ]); });
Ein change-event auslösen.
var the_element_id = 'some_id'; $('#' + the_element_id).trigger('change');
Events verarbeiten
var the_event = 'some_event'; $(document).on(the_event, {}, function(e, id, val) { if(val <= 0) { $('#another_element').hide(); } else { $('#another_element').show(); } });
Konkretes Beispiel aus der WordPress Welt
<?php class SelectControl { function __construct($args) { $this->args = wp_parse_args(array( 'title' => '', 'options' => array(), 'value' => false, 'name' => wp_generate_password(8, false, false), // s.th. unique 'jsevent' => false, 'id' => wp_generate_password(8, false, false) // s.th. unique ), $args); /* $args['options] = array( array( 'name' => 'foo', 'value' => '-1' ), array( 'name' => 'foobar', 'value' => '0' ), array( 'name' => 'bar', 'value' => '1' ) ); */ add_action('wp_footer', array($this, 'javascript')); } function html() { $a = $this->args; // This smells. But its ok, the only variable around here. ?> <label><?= $a['title'] ?></label> <select class="form-control" name="<?= $a['name'] ?>" id="<?= $a['id'] ?>"> <?php foreach($a['options'] as $option) : ?> <option <?php if($option['value'] == $a['value']) : ?>selected<?php endif; ?> value="<?= $option['value'] ?>"><?= $option['name'] ?></option> <?php endforeach; ?> </select> <?php } function javascript() { $a = $this->args; if($a['jsevent']) : ?> <script> jQuery(document).ready(function($) { $('#<?= $a['id'] ?>').change(function() { $(document).trigger('<?= $a['jsevent'] ?>', [ '<?= $a['id'] ?>', $('#<?= $a['id'] ?>').val() ]); }); }); </script> <?php endif; } } ?>
<?php class FancyTextControl { function __construct($args) { $this->args = wp_parse_args(array( 'title' => '', 'value' => false, 'name' => wp_generate_password(8, false, false), // s.th. unique 'jsevent' => false, 'id' => wp_generate_password(8, false, false) // s.th. unique ), $args); add_action('wp_footer', array($this, 'javascript')); } function html() { $a = $this->args; // This smells. But its ok, the only variable around here. ?> <label><?= $a['title'] ?></label> <input type="text" class="form-control" value="<?= $a['value'] ?>" name="<?= $a['name'] ?>" id="<?= $a['id'] ?>"> <?php } function javascript() { $a = $this->args; if($a['jsevent']) : ?> <script> jQuery(document).ready(function($) { $(document).on('<?= $a['jsevent'] ?>', {}, function(e, id, val) { // Argument id is the ID of the caller. $a['id'] is the ID of the text input control. $('#<?= $a['id'] ?>').text(val); }); }); </script> <?php endif; } } ?>
Weitere Informationen
api.jquery.com/category/events/
api.jquery.com/trigger/
api.jquery.com/on/