簡體   English   中英

jQuery +一個返回被點擊元素的函數

[英]jQuery + A function that returns clicked element

我已經堅持了很長一段時間了,我正在尋找一些指導...我想把以下內容變成更有活力的東西。 我希望'selector'能夠根據點擊的元素進行更改。

所以這就是我認為需要做的事情:

  1. 弄清楚點擊了哪個元素。 (h1,p,ol)
  2. 現在在變量中使用該元素,將類似的函數應用於我在下面創建的函數。

否則,我必須為每個元素實例指定相同的函數。 (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)

  • 對於每種不同的元素類型(h1,h2,p) - 一次只顯示一個。 (默認情況下,每個el的第一個開始。)
  • 當您單擊該元素時,它會循環顯示相同的元素兄弟。 (h1將隱藏當前的h1,並顯示下一個h1,當它到達end / last h1時,它會重新啟動循環)

如果要將選擇器應用於多個不同的DOM元素,可以使用逗號分隔選擇器:

$('h1,p,ol').click(function(){ })

看看jquery多個選擇器

你可以通過幾種方式做到這一點

$("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訪問被點擊的元素

這里是小提琴http://jsfiddle.net/6gCRF/

您可以使函數動態如下:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM