2015-11-06 26 views
2
<span class="switchery switchery-small" style="box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); transition: border 0.4s, box-shadow 0.4s; background-color: rgb(255, 255, 255);"> 
    <small style="left: 0px; transition: background-color 0.4s, left 0.2s;"></small> 
</span> 

我正在使用插件並生成上面的代碼。我如何選擇它的左邊是0px的小標籤的切換臺?具有「left:0px」的元素上的綁定事件

我寫這

if ($('.switchery').find('small').attr('style').indexOf('0px') > -1) { 

} 

,但我怎麼能申請click()我的比賽元素。

回答

0

使用filter與回調。

  1. 選擇所有.switchery元素
  2. 篩選具有元素left財產零

var smallEl = $('.switchery small').filter(function() { 
 
    return parseInt($(this).css('left')) === 0; 
 
}).css('color', 'green'); 
 

 
smallEl.click(function() { 
 
    console.log('Hello'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<span class="switchery switchery-small" style="box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); transition: border 0.4s, box-shadow 0.4s; background-color: rgb(255, 255, 255);"> 
 
    <small style="left: 0px; transition: background-color 0.4s, left 0.2s;">Left 0</small> 
 
    <small style="left: 100px; transition: background-color 0.4s, left 0.2s;">Left 100</small> 
 
    <small style="transition: background-color 0.4s, left 0.2s;">No Left</small> 
 
</span>

+0

哇不知道過濾器可用於這個樣子!真棒!但使用.css('顏色',綠色)是否是苛刻的?那個有什麼用途? –

+0

@JenniferAniston這只是爲了Demo的目的。給視覺線索返回「過濾器」的結果。 – Tushar

+0

所以沒關係.css()不在那裏? –

0

你可以這樣寫裏面的<small>元素:

if ($('.switchery').has('small').find('small').css('left') == '0px') { 
    // if matches 
    // do click operation here 
    $('.switchery').click() 
    // or 
    $('.switchery').click(function() {... 
    }); 
} 

DEMO

+0

** 1 **不需要''有('小')'。 ** 2 **如果有多個元素'.find('small').css('left')'不會按預期工作** 3 * OP想要在具有'left:0px; 。 ** 4 **這不符合預期。檢查更新[演示](https://jsfiddle.net/tusharj/4ya36vag/2/)。 – Tushar

+0

是的,似乎是這樣。 –

+0

我必須使用$(this),因爲我有更多標籤。 –

0

嘗試使用選擇$(".switchery small[style*='left\\: 0px']")

$(".switchery small[style*='left\\: 0px']").click(function() { 
 
    alert(this.textContent) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<span class="switchery switchery-small" style="box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); transition: border 0.4s, box-shadow 0.4s; background-color: rgb(255, 255, 255);"> 
 
    <small style="left: 0px; transition: background-color 0.4s, left 0.2s;">0px</small> 
 
</span> 
 
<span class="switchery switchery-small" style="box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); transition: border 0.4s, box-shadow 0.4s; background-color: rgb(255, 255, 255);"> 
 
    <small style="left: 1px; transition: background-color 0.4s, left 0.2s;">1px</small> 
 
</span>

相關問題