简体   繁体   中英

How to call jquery plugin function using `onlick attribute` in HTML

Just as we call regular javascript functions from onclick attribute, why can't we call jQuery methods as shown in the following code. Why does this not work?

<body>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
  <p id="p1">Some Text inside paragraph</p>
  <button type="button" onclick="$.test();">Click Me</button>
</body>

JS

$.fn.extend({
  test: function() {
    var t = $('#p1').text();
    alert(t);
    });
  },
});

thanks bt

Keeping the issue of using onclick= aside, you can do it this way:

<p id="p1">Some Text inside paragraph</p>
<button type="button" onclick="$(this).test();">Click Me</button>

and

$.fn.extend({
  test: function() {
    var t = $(this).text();   // use $(this) here
    alert(t);
  },
});

Example fiddle: https://jsfiddle.net/asw8824h/

$(document).ready(function () {
    $(document).on('click',"#target",function () {        
        // do something
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM