On Sep 15, 6:09 pm, sirrocco <xavier...@gmail.com> wrote:
> Let's say you have a :
>
> <a href="#" onclick='DoSomething(this);'>asd</a>
>
> I want to get the onclick text in a variable - something like
>
> var onclick = $('a').attr('onclick');
>
> The problem is that the onclick variable now is a function and if I
> try to execute , this   wil be the document instead of the link .

That is (in part) because the attr method returns a reference to the
function object, i.e. it returns the DOM property, not the HTML
attribute.


> How can I get only the text,

You could try the getAttribute method, but it's buggy in IE:

  var listenerCode = element.getAttribute('onclick');


> so I can later reattach it to the link ?

There are a couple of methods, buy you need to change how your
function works and understand the difference between an HTML attribute
and a DOM element property.

The text supplied in the onclick attribute is converted to a function
and is called by the onclick handler when a click event occurs. When
attached inline, the handler sets the function's this keyword to a
reference to the element that the handler belongs to.

When attached as a property of a DOM element, browsers like Firefox
continue to set this to the element, but browsers like IE don't so
this resolves to the global object (per the ECMAScript specification).

One way to fix the issue is to use the event object rather than the
this keyword so the function can be assigned to other elements simply
by assigning it to the appropriate DOM property, e.g.

<script type="text/javascript">

window.onload = function() {
  var el0 = document.getElementById('a0');
  var el1 = document.getElementById('a1');
  el1.onclick = el0.onclick;
}

function foo(evt) {
  var evt = evt || window.event;
  if (!evt) return;
  var el = evt.target || evt.srcElement;
  alert('id: ' + el.id);
}
</script>

<a id="a0" href="#" onclick="foo(event);">a0</a>
<a id="a1" href="#" >a1</a>


Another method is to use event delegation and listen for the event
higher up the DOM tree so you don't need to assign the listener to new
elements.


--
Rob

Reply via email to