开发者

Can I assign an action from javascript dynamically?

Typically, I do this to prompt the alert box, and say Hello

<div style="color:#00FF00" onclick=alert("Hello"); id = "helloDivTag">
  <h3>This is a header</h3>
  <p>This is a paragraph.</p>
</div>

But this time, I don't want to do it inside the html tag, I want to do it inside the js. How can I do so? Thank yo开发者_C百科u.


i would recommend using the jquery framework then you just do this

$(function(){
$('#helloDivTag').click(function(){
alert("Hello");
});
});

implementing it would look like this you just put it in the header

<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$(function(){
    $('#helloDivTag').click(function(){
    alert("Hello");
    });
    });
</script>

why i recommend using jquery and not simple javascript is because there is alot of other functionality that could get in handy almost everytime you want to do something


window.onload = function() {
    document.getElementById('helloDivTag').onclick = function(){
        alert('hi');
    }
}

when the window loads the click event is attached to your div and whenever you do the clicks the alert happens. This is called seperating behvaiour from structure and style.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜