开发者

javascript: How to assign a function to an element

开发者 https://www.devze.com 2022-12-28 13:40 出处:网络
Here\'s what I want: I have anelement in my html code, and I want to assign a function to the onClick e开发者_Go百科vent, depending on some conditions to be known down the road.

Here's what I want:

I have an element in my html code, and I want to assign a function to the onClick e开发者_Go百科vent, depending on some conditions to be known down the road.

For example

<a href="" id = "element"><img .....>

//other code

</a>

Then I want to do something like this

 <logic:equals some_condition>
      <script>
           var e = document.getElementById("element");

           e.onClick = my_function();

      </script>
 </logic>

But I cant get it working. Is there any special syntax?

I've tried with

 e.onClick = my_function;
 e.onClick = function(){my_function();}

Sadly i'm in IE 6.

Thanks in advance.


  1. You should give <script> a type attribute:
  2. The method to get the reference to an element by id is called getElementById
  3. onclick (as all of JavaScript) is case-sensitive:
  4. You assign a reference of a function to event handlers, thus you leave the parenthesis away other wise it will call the function then and there.

.

<script type="text/javascript">
  var e = document.getElementById("element");
  e.onclick = my_function;
</script>

EDIT: If the logic is server-side its probaly easier to set then event handler in the HTML code then:

<a href="" <% if (some_condition) print "onload='my_function();'" %>>

(That is pseudo code, depending on you server-side language)


onclick is case sensitive

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号