OnClick snap function in another area

I am trying to associate a function with an onclick binding. I do not use traditional jQuery bind / live / on / whatever, because I have other scripts that stop event propagation (this sucks, I know).

To associate a function with the onclick attribute, I pass the JSON object to the module as follows:

function foo() { alert('foo') } $('document').ready(function() { var options = { opt1: 'fooID', opt2: 'barID', json: mightyJSON, actions: [ { url: 'contact/_id_/edit', text: "Edit", iconPath: 'edit.png' }, { url: '#', onClick: foo, text: "Delete", iconPath: 'delete.png' } ] }; var trolol = myModule.configure(options); }); 

As you can see, a function called "foo" is passed through the "onClick" JSON property. The function is defined above the object.

In "myModule" I create an anchor tag as follows:

 var buildLinks = function(objectID) { var linksNbr = actions.length; var link, cssClass; for (var i = 0; i < linksNbr; i++) { // Adding the object ID to the URL link = actions[i].url.replace('_id_', objectID); cssClass = actions[i].cssClass || ''; var $link = $(document.createElement('a')).attr('onClick', actions[i].onClick) .attr('href', link) .attr('title', actions[i].text) .addClass(cssClass) .text('foo'); } return $link.html(); }; 

The fact is that, as you can expect, "foo" is executed when the script is parsed and only there. "Onclick" doesn't even work after.

I can describe this as onClick: 'foo()' . The onclick job works, but it also does the parsing, and this, in my opinion, is very ugly.

I would still be able to pass it like this onClick: foo , but it worked correctly (i.e. it was not executed at boot time, but only when clicked.

It should work with jQuery 1.4.4, unfortunately.

+4
source share
3 answers

I would do it like this:

 var $link = $('<a></a>',{ href : link, title : actions[i].text, 'class' : cssClass, text : 'foo', click : actions[i].onclick }) return $link; 

Then use one of them ( 1 , 2 ) to insert the node, which is an html with events.


for the distribution problem, I would do something like this:

html <a href="#no" ....>text</a>

js $('a[href="#no"]').live('click',function(){ return false; });

This way, when href points to #no , the event eventually propagates

0
source
  • if at all possible, return the element, not its .html()

  • .attr('onclick', ...) done this, do not use .attr('onclick', ...) , when you already have a link to a function, use .prop or even just element.onclick = ...

eg.

 $link = $('<a>', { href: link, title: actions[i].text, 'class': cssClass, text: 'foo' }).prop('onclick', actions[i].onClick); 
0
source

The following is a snippet of the script . If this approach is fine, you can, as shown below, set onclick to the jquery raw element, for example:

 $link[0].onclick = options.actions[i].onClick; 
0
source

All Articles