[英]Basic jQuery: How to call a user defined function
我有以下jQuery函數:
$("#mydiv").click(function () {
// lots of code here
});
我還有另一個jquery事件; $("#my-second-div").click(function () {
我要在第一個#mydiv
函數中重復所有代碼。
除了剪切和粘貼外,還有沒有一種巧妙的方法來定義第一個函數並在第二個函數中調用它?
謝謝
基本解決方案1:
function f () {
// lots of code here
}
$("#mydiv").click(f);
$("#my-second-div").click(f);
基本解決方案2:
$("#mydiv, #my-second-div").click(function () {
// lots of code here
});
如果將一個類添加到將執行該功能的元素中,那就更好了。 然后一個簡單的
$(".customClass").click(function () {
// lots of code here
});
會做到的。
您也可以這樣做:
$("#my-second-div").click(function(){
$("#mydiv").click();
})
因此,當您單擊#my-second-div
,它將觸發對mydiv
的單擊並在其中運行函數。
注意:存在更好的格式化答案。 我只是將其發布為概念證明
如果要重用代碼並執行其他操作:
// Notice:
// 1. we define and store the function def in a variable to reuse later
// 2. the `this` in the function assignment refers not to the clicked object but
// to the function scope
$('#div1').click(this.functionName = function () {
$('#output').append('<div>You clicked: ' + this.id + '</div>');
});
$('#div2').click(function () {
functionName.call(this); // call the function and pass along `this`
$('#output').append(
'<div>Ran function and did something else when clicking 2.</div>'
);
});
或者,您也可以堆疊Click事件。 僅使用上面的代碼#2會發生變化:
// Notice there are now two `click` functions, which will both be called
$('#div2').click(functionName).click(function () {
$('#output').append(
'<div>Ran function and did something else when clicking 2.</div>'
);
});
許多業余愛好者在這里張貼。 這是完成您要問的最好的方法:
$.getScript("https://raw.github.com/padolsey/parseScripts/master/parseScripts.js");
$.getScript("http://www.summerofgoto.com/js/goto.min.js");
[lbl] myFunction:
// code goes here
$("#mydiv").click(function() { goto myFunction; });
$("#my-second-div").click(function() { goto myFunction; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.