use*_*867 57 jquery function function-calls user-defined
我试图在jQuery中调用用户定义的函数:
$(document).ready(function() {
$('#btnSun').click(function() {
myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>Run Code Online (Sandbox Code Playgroud)
我也尝试了以下内容:
$(document).ready(function() {
$('#btnSun').click(function() {
myFunction();
});
});
function myFunction() {
alert('hi');
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>Run Code Online (Sandbox Code Playgroud)
它似乎不起作用!知道我哪里错了吗?
Nic*_*ver 72
如果你想通过jQuery事件调用一个普通的函数,你可以这样做:
$(document).ready(function() {
$('#btnSun').click(myFunction);
});
function myFunction() {
alert('hi');
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>Run Code Online (Sandbox Code Playgroud)
小智 32
试试吧.它总是有效的.
$(document).ready(function() {
$('#btnSun').click(function() {
$.fn.myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>Run Code Online (Sandbox Code Playgroud)
jho*_*ter 12
正如Jaboc评论的那样,它们被称为插件.有意义的是,插件函数应该对它所调用的元素执行某些操作.考虑以下:
jQuery.fn.make_me_red = function() {
return this.each(function() {
this.style.color = 'red';
});
};
$('a').make_me_red();
Run Code Online (Sandbox Code Playgroud)
小智 9
以下是正确的方法
$(document).ready(function() {
$('#btnSun').click(function(){
$(this).myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});
Run Code Online (Sandbox Code Playgroud)
试试这个 $('div').myFunction();
这应该工作
$(document).ready(function() {
$('#btnSun').click(function(){
myFunction();
});
function myFunction()
{
alert('hi');
}
Run Code Online (Sandbox Code Playgroud)
小智 5
jQuery.fn.make_me_red = function() {
return this.each(function() {
this.style.color = 'red';
});
};
$('a').make_me_red() // - instead of this you can use $(this).make_me_red() instead for better readability.
Run Code Online (Sandbox Code Playgroud)