2017-04-27 114 views
0

內按下按鈕的按鈕文本我有兩個按鈕中的跨度獲得元素

<span class="somespan"> 
<button type="button">left</button> 
<button type="button">right</button> 
</span> 

我已成立的.on事件時一個被激活來觸發。

$('.somespan').on("mousedown tap", function() { 
direction = ($(this).text()); 
}) 

這產生結果leftright,因爲它提供了所有按鈕的按鈕文本。我怎樣才能得到點擊按鈕的按鈕文本?

+0

attatch聽者的按鈕;) – Mazz

+0

所以你要特別點擊的按鈕標題? –

回答

1

的問題是,因爲你已經附加了事件的span。對於this來指代button元素,您需要將該事件附加到該元素。試試這個:

$('.somespan button').on("mousedown tap", function() { 
 
    direction = $(this).text(); 
 
    console.log(direction); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="somespan"> 
 
    <button type="button">left</button> 
 
    <button type="button">right</button> 
 
</span>

另外,如果你有選擇span,那麼你可以通過使用event.target代替this發現點擊的元素。注意處理函數參數中的e

$('.somespan').on("mousedown tap", function(e) { 
 
    direction = $(e.target).text(); 
 
    console.log(direction); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="somespan"> 
 
    <button type="button">left</button> 
 
    <button type="button">right</button> 
 
</span>

0

你要監聽attatch的按鈕:)

$('button').on("mousedown tap", function() { 
    direction = ($(this).text()); 
}) 

或在跨度

$('.somespan').on("mousedown tap","button", function() { 
    direction = ($(this).text()); 
}) 
0

嘗試增加

$('.somespan button').on("mousedown tap", function() { 
direction = ($(this).text()); 
}) 

在你的情況,你所添加的鼠標按下事件的跨度,而不是按鈕

0

您選擇更改從$('.somespan')$('.somespan>button')針對具體的button

$('.somespan>button').on("mousedown tap", function() { 
 
    var direction = $(this).text(); 
 
    console.log(direction) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="somespan"> 
 
    <button type="button">left</button> 
 
    <button type="button">right</button> 
 
</span>

+0

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –