开发者

Reuse a Jquery Script

I'm trying to reuse a function 开发者_如何学编程i made, but with any help yet.

Here is my index.html.

<html>
<head>
<script src="jquery-1.5.1.js")" type="text/javascript"></script>
<script src="JqueryScript.js")" type="text/javascript"></script>
<script type="text/javascript"> 
    //MYLIBRARY.init(['#button1']);
    execute(['#button1']);
    execute(['#button2']);
</script>
</head>
<body>
<button type="button" id="button1">Click Me!</button>
<button type="button" id="button2">Click Me!</button>
</body>
</html>

And here is my script.

function execute (Args){
    _args = Args;
    $(function() {
        $(_args[0]).click(function() {
          alert("hello " + _args[0]);
          return false;
        });
    });
}

The problem is always triggers the second alert windows (#button2). How can i make it work with both alert windows?


My guess is that you are wondering why both buttons alert the same output.

Because _args is global. Thus the second invokation will overwrite _args.

Use var to make it local:

var _args = Args;

Your code could still be improved (see @Town's answer), but this should get you started.


You also have errors in your HTML

<script src="jquery-1.5.1.js")" type="text/javascript"></script>
<!--                         ^^                              -->
<script src="JqueryScript.js")" type="text/javascript"></script>
<!--                         ^^                              -->


What exactly are you trying to do?

From what I can see, you could achieve the same functionality as what you have with simply:

$(function() {
    $('button').click(function() {
        alert("hello #" + this.id);
    });
});

Example


Looks like C to me :)

You'd be better off with

<script type="text/javascript"> 
$(function () {
   execute('#button1');
   execute('#button2');
}

function execute(buttonId)
{
    $(buttonId).click(function () { alert('Hello ' + this.id); });

}

</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜