簡體   English   中英

jQuery:當它們共享相同的CSS類時,如何定位被點擊的元素?

[英]jQuery: How do I target the clicked element when they all share the same CSS class?

我的頁面上有3個div元素,每個元素都有一個相同的CSS類“.shape”

在我的JS中,我希望將當前單擊“.shape”作為目標,以便使用jQuery slideDown過渡將一些額外的html插入到“.shape”的底部。

當你再次點擊“.shape”時,額外的html將會滑動。

我該如何輕松地做到這一點? 是)我有的:

$(".shape").click(function() {
    var id = $(this).attr("id");
    var selected = id + "-reveal";
});

在我的HTML中,

<div class="shape" id="shape1">Content</div>
<div class="hidden" id="shape1-reveal">Content</div>

<div class="shape" id="shape2">Content</div>
<div class="hidden" id="shape2-reveal">Content</div>

<div class="shape" id="shape3">Content</div>
<div class="hidden" id="shape3-reveal">Content</div>

我也不知道如何添加切換+滑動效果。

編輯:解決方案http://codepen.io/vennsoh/pen/rVjeQy

不確定我編寫JS的方式是否是最優雅的方法。

定位用$(this)點擊的元素

$(".shape").click(function() {
    var clickedShape = $(this);
});

一旦你有了$(this) ,你就可以用find()來定位它里面的元素。

或者在HTML的情況下,使用next()在形狀后找到reveal元素。

找到合適的元素后,可以使用slideUp()slideDown()slideToggle()

$(".shape").click(function() {
    var revealThing = $(this).next();

    revealThing.slideToggle();
});

http://jsfiddle.net/yopp6L22/1/

正如評論所說,你已經按照使用$(this)點擊的形狀進行操作......你還沒有做任何事情,所以你沒有意識到這一點。

許多切換工作是通過向要顯示/隱藏的元素添加和刪除類來實現的。

所以,如果你有css:

.hidden { display:none }
.visible { display:block }

然后你可以通過將visible類添加到被點擊的元素來切換可見性,如下所示:

$(".shape").click(function() {
  if($(this).hasClass("visible")) { $(this).removeClass("visible"); }
  else { $(this).addClass("visible"); }
});

在jQuery中,當你在事件處理程序回調函數中時,'this'關鍵字指的是觸發事件的元素。

因此,在您的示例中,當您單擊具有“shape”類的元素時,它將觸發回調函數(因為事件已附加到具有“shape”的所有元素)。 但是在任何給定時間只會觸發1個回調,並且該回調將引用啟動事件的特定DOM元素(即正確的div)。

它在普通javascript中的工作方式也可以,如果你將一個事件參數傳遞給你的回調,你可以訪問event.target和event.currentTarget屬性(這是相對於被觸發事件的DOM元素引用)。 currentTarget通常等於'this'。 https://api.jquery.com/event.currentTarget/

你肯定會在大多數時候使用它,因為它更簡單。 但是在更高級的情況下,this關鍵字可能通過綁定得到ovverridden,那么event.currentTarget是一個穩定的回退。

$(".shape").click(function(event) {
   var whatGotClicked = event.currentTarget;
   var whatGotClicked = this; //both wor
});

TL; DR簡而言之,你所擁有的將會很好,但我希望你對這個原因有更深入的了解。

從哪里去?

$(".shape").click(function() {
    var id = $(this).attr("id");
    var selected = $(id + "-reveal"); //this will give you a jQuery object targeting the selected id of the reveal element
    selected.toggle(); //at this point you decide, jQuery has alot of helper methods, like slideDown() and slideUp or .animate
});

https://api.jquery.com/?s=toggle

這是jquery代碼,用於警告所單擊元素的id

$('.shape').on('click', function(event) {
    alert(event.target.id);
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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