如何在 HTML 中使用“onclick 属性”调用 jquery 插件函数

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

正如我们从onclick属性调用常规javascript函数一样,为什么我们不能调用jQuery方法,如下面的代码所示。为什么这不起作用?

<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);
    });
  },
});

谢谢 bt

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

暂且不提使用onclick=的问题,你可以这样做:

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

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

示例 fiddle:https://jsfiddle.net/asw8824h/