javascript - How can I assign a delegated jQuery event listener based on values in jQuery's data API? -
jquery treats data-attributes in interesting way, wherein retrieves values once , not observe changes or removals after point. modification of data achieved using jquery's various functions – $element.data('key', 'val')
etc. such, muddies code things $element.prop('data-key', 'val')
, $element.removeprop('data-key', 'val')
because does not touch jquery data api, though reasonably appear these calls intended that.
however, means of altering dom seems way use data-attributes delegated event listeners "the jquery way:"
$element.on('click', '[data-key=val]', function(e) { // triggers on children of $element have dom attribute // data-attribute data-key, value of val });
data-attributes don't clog classnames etc , seem reasonable place put element attributes javascript usage. if write $element.find('div').data('key', 'val')
, these elements not meet criteria when clicked. way accomplish saying $element.find('div').prop('data-key', 'val')
, not best practice understand it.
the other option this:
$element.on('click', 'div', function(e) { if ($(this).data('key') != 'val') return; // handle });
this seems clunky, , trigger more above. it's little less clear we're targeting.
were not delegated, write:
$element.find('div') .filter(function() { return $(this).data('key') == 'val'; }) .on('click', function(e) { // handle });
but .filter()
won't work delegated listeners, accept string selector.
so problem this: have multiple solutions already, none ideal, , none follow jquery's idiom. how can assign delegated listeners based on jquery data api?
try utilizing htmlelement.dataset
$(document).on("click", "[data-clickable=true]", function(e) { alert(this.dataset.clickable) }); // set `div` `dataset.clickable` `true` $("button").on("click", function() { $("div")[0].dataset.clickable = true; $("[data-clickable=true]").html("clickable: true") });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <button>make `div` "clickable"</button> <div data-clickable="false">clickable: false</div>
jsfiddle http://jsfiddle.net/a7qcafwf/1/
Comments
Post a Comment