Reading jQueryUI dialog code, I’ve found out, jQuery .attr() method has some undocumented behavior:
<button id="btn1">1</button>
<button id="btn2">2</button>
$(function() {
var props = {
text: 'Click it!',
click: function () {
console.log('Clicked btn:', this);
}
};
$('#btn1').attr(props, true); // Changes #btn1 inner text to 'Click it!'
// and adds click handler
$('#btn2').attr(props); // Leaves #btn2 inner text as it is and fires
// click function on document ready
});
- Can you explain me how it works? Why should I set
trueas the second argument after
map of attribute-value pairs? - Can I use this feature in my projects safely?
I’m guessing slightly here because I’m unfamiliar with the jQuery source.
jQuery.attrcallsjQuery.access, and the comment above the jQuery.access function reads:Upon further investigation, the
text()function also callsjQuery.access:You’re using attr to set text and event handlers, which is not what attr is for. However they all seem to be using the same function to get the job done, so the use of undocumented parameters is just incidentally giving you the expected behavior.
I would consider it unreliable to rely on undocumented behavior to accomplish what you’re trying to do here, as any future upgrade of jQuery could break your code.