如何在JQuery中创建自己的函数?
如何创建自己的函数并调用另一个函数?像-如何在JQuery中创建自己的函数?,jquery,Jquery,如何创建自己的函数并调用另一个函数?像- $('.mycls li').hover(function() { var divid = $(this).find('li').attr('some_attr'); call myfunc(divid); }); function myfunc(divid) { $(divid).show(); //I want to hide rest all divs $('div#info1').hide(); $('div#info2').hide
$('.mycls li').hover(function() {
var divid = $(this).find('li').attr('some_attr');
call myfunc(divid);
});
function myfunc(divid)
{
$(divid).show();
//I want to hide rest all divs
$('div#info1').hide();
$('div#info2').hide();
$('div#info3').hide();
}
我有两个问题,一个是如何在jquery中实现这个逻辑,第二个是哪个属性可以用来将特定的li引用到特定的div
我的div是-
<div id="info1">
//some information
</div>
<div id="info2">
</div>
....
//一些信息
....
您的函数应该能够像jquery的其他方法/函数一样在包装集上操作。考虑插件,很容易:
或参阅:
调用函数时不需要使用关键字
call
。所以就用
myfunc(divid);
调用你的函数就可以了
要将您的li
-s链接到您的div
-s,您可以使用一个id命名方案,例如,给您的li
-s id以d开头,给您的div
id以“info”开头,但后面的位相同
<li id='d1'> </li>
<li id='d2'> </li>
<li id='d3'> </li>
<div id='info1'></div>
<div id='info2'></div>
<div id='info3'></div>
我写道:
jQuery.fn.doSomeStuff = function(options, callback) {
var $elem = $(this[0])
var args = options || {};
// doSomeStuff
alert("DOM element: "+$elem.html());
alert("this ia a parameter:"+ args.aParameter);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
return $elem; //ensures jquery chainability
};
您可以试一试您已经回答了第一个问题。至于第二个。。。我不明白,请澄清。我认为您必须显示更多的HTML标记。@Kling我只想在li项的mouseover上调用myfunc()。看看我的代码是否正确-$('.smenu li').mouseover(function(){myfunnc();});jQuery.fn.myfunc=function(){$('div#telcosinfo').show(“medium”)}它的意思是
div
-s id必须像1,2,3…?
不,div
-s id必须像info1,info2,info3
-我已经更新了我的答案,让它更清楚了……但即使在我通过divid时,它也不起作用=“info1”;myfunc(divid);
它没有调用该函数,但页面的所有div
-s都消失了。
jQuery.fn.doSomeStuff = function(options, callback) {
var $elem = $(this[0])
var args = options || {};
// doSomeStuff
alert("DOM element: "+$elem.html());
alert("this ia a parameter:"+ args.aParameter);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
return $elem; //ensures jquery chainability
};