开发者

Question | Jquery plugin creation problem

开发者 https://www.devze.com 2023-04-01 19:22 出处:网络
Why isn\'t this working? ---HTML-------- <html> <head> <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js\"></script>

Why isn't this working? ---HTML--------

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="j.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.createHello();
});
</script>
</body>
</html>

---JS---------j.js-------

(function($){  
 $.fn.createHello= function() {  
    $('body').append('<div id="hello">Hello world</div>');
    $('#hello').click(funciton(){
    alert("Hello you clicker");
    });
 };  
})(jQuery); 

Any solutions, or bet开发者_Go百科ter ways to do the same thing?


Change the click to delegate since you are creating the hello element on the fly. Below is the updated code. Also function was misspelled,

Live Demo

 $.createHello = function() {  
    $('body').append('<div id="hello">Hello world</div>');
    $('body').delegate('#hello', 'click', function(){
        alert("Hello you clicker");
    });
 } 

$(document).ready(function(){
    $.createHello();
});

Personally this is how I would write it:

Updated Demo

 $.fn.createHello = function() {  
    $(this).append('<div id="hello">Hello world</div>');
    $(this).delegate('#hello', 'click', function(){
        alert("Hello you clicker");
    });
 } 

$(document).ready(function(){
    $('body').createHello();
});

This allows you to tie it to any element on the page and call createHello()

I also suggest checking out the plugin authoring reference for some good tips.


since you defined the plugin using $.fn.myPlugin, you have to select an element for the plugin to work on. If you wish for the plugin to work in the way that you are using it, define it with

$.myPlugin = function(){
  // your code here
}


createHello plugin is appending a div with some content to the body element. In order to attach a click event you should select the element and the refer to it using this keyword inside the plugin code. Try something like this

Add this markup in your test page

<div id="hello">Click me</div>

JS

 $.fn.createHello= function() {  
    $('body').append('<div id="hello">Hello world</div>');
    this.click(funciton(){
       alert("Hello you clicker");
    });
 };  


$("#hello").createHello();
0

精彩评论

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

关注公众号