[英]jQuery + A function that returns clicked element
我已經堅持了很長一段時間了,我正在尋找一些指導...我想把以下內容變成更有活力的東西。 我希望'selector'能夠根據點擊的元素進行更改。
所以這就是我認為需要做的事情:
否則,我必須為每個元素實例指定相同的函數。 (h1,h2,h3,p,ul,ol)
到目前為止,這就是我所擁有的:(有效,但顯然僅適用於我的h1元素)
$("#content_body h1").click(function() {
$(this).hide(); //hide current element.
$(this).next().show(); //display next element.
var numofEl = $("#content_body h1").length;
if ($(this).next().index() == numofEl) { //if we're at last element,
$("h1:first-child").show(); //restart cycle.
}
});
任何幫助總是非常感謝..提前感謝!
* 更新 **
把這個/描述我想要得到的另一種方式:
假設您在容器中有許多不同的元素。 (例如> #content_body)
如果要將選擇器應用於多個不同的DOM元素,可以使用逗號分隔選擇器:
$('h1,p,ol').click(function(){ })
你可以通過幾種方式做到這一點
$("h1,p,ol,div").bind("click",function(){
//write the generic code here
});
也(由8vius
建議)
$('h1,p,ol,div').click(function(){
//write the generic code here
})
在處理程序中,您可以通過$(this)
或this
訪問被點擊的元素
您可以使函數動態如下:
showHide('h1');
showHide('p');
showHide('ol');
function showHide(element){
$(element).click(function() {
$(element).hide(); //hide current element.
$(element).next().show(); //display next element.
var numofEl = $(element).length;
if ($(element).next().index() == numofEl) { //if we're at last element,
$(element).eq(0).show(); //restart cycle.
}
});
}
這是你想要的嗎?
var length = $("#content_body").children().length;
$("#content_body").children().each(function(index){
$(this).click(function() {
$(this).hide(); //hide current element.
$(this).next().show(); //display next element.
if (length-1 == index) { //if we're at last element,
$("h1:first-child").show(); //restart cycle.
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.