2017-10-16 102 views
-1

我花了幾個小時試圖解決這個問題,並審查其他類似的StackOverflow問題(1)(2),但沒有似乎有回答我的問題..的jQuery + Rails的:如何獲得按鈕用戶的ID點擊

我無法通過此錯誤:ReferenceError: id is not defined。警報不顯示。

$("button.btn-tag-cat").click(function(e){ 
    e.preventDefault(); 
    var id = $(this).prop('id'); 
    alert(id); 
    id.find('span').show(); 
    }, function(){ 
    id.find('span').hide(); 
    }); 

我試過以下方法來使用id變量但沒有工作。

$(id).find('span').show(); 
$("#" + id).find('span').show(); 

然而,當我刪除的警報下面的代碼塊,警報會彈出屬於按鈕正確的ID。

$("button.btn-tag-cat").click(function(e){ 
    e.preventDefault(); 
    var id = $(this).prop('id'); 
    alert(id); 
    }); 

查看部分: 按鈕的ID引用紅寶石局部變量id="<%= name %>"

<% q.categories_name_in.each do |name| %> 
    <button type="button" class="btn btn-outline-primary btn-lg btn-tag-cat" id="<%= name %>"><%= name %><span class='glyphicon glyphicon-remove'></span></button> 
    <% end %> 

回答

2

正如您所指出的那樣,誤差在點擊鏈接收聽功能。

爲了獲得id屬性,你可以使用jQuery的attr功能,如:

$("button.btn-tag-cat").click(function(e) { 
    e.preventDefault(); 
    var id = $(this).attr('id'); 
    alert(id); 
    $('#' + id).find('span').show(); 
}); 

$("button.btn-tag-cat").click(function(e) { 
 
    e.preventDefault(); 
 
    var id = $(this).attr('id'); 
 
    alert(id); 
 
    $('#' + id).find('span').show(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button class="btn-tag-cat" id="hallo">Press</button>

1

在這裏,你的代碼,我會美化它,看看你的錯誤:

$("button.btn-tag-cat").click(
    function(e) { 
    e.preventDefault(); 
    var id = $(this).prop('id'); 
    alert(id); 
    id.find('span').show(); 
    }, 

    function() { 
    id.find('span').hide(); 
    } 
); 

不是冰第二個函數具有

function() { 
    id.find('span').hide(); // right here 
    } 

但ID沒有被定義尚未

嘗試

function() { 
    var id = $(this).prop('id'); // this first 
    id.find('span').hide(); 
    } 
+0

感謝明確的答覆,但是,我現在收到此錯誤:類型錯誤:id.find不是函數 – doyz

+0

使用'$(id)'代替id。 –

+0

該ID是一個字符串。使用'$('#'+ id).find(...)' –

相關問題