2016-06-13 20 views
0

我有這樣的代碼.attr()在屬性選擇一個變量不行

<div class="field"> 
    <label>Title</label> 
    <input id="post-titie" type="text"> 
</div> 
<div class="ui olive message" for-field="post-title" hidden> 
    <div class="header">About Title</div> 
    <ul class="list"> 
     <li>Visitors can see your title even if they're not logged in.</li> 
     <li>The title is public.</li> 
    </ul> 
</div> 
​​

我想要做的就是當<input><textarea>集中,顯示的信息與DIV .message類。

我將$(this).attr('id')作爲變量(例如,post-title),並通過.find('div[for-field="'+forwhom+'"]')找到它。這不起作用。

但是,如果我將var forwhom$(this).attr('id')(jQ選擇器)替換爲絕對值,如post-title,它確實有效。

很奇怪!根據jQuery文檔,.attr()方法返回的字符串不是對象。

什麼問題?

+0

只需試試這個'$(':input')'因爲:input是一個jquery擴展 – gurvinder372

+0

當我嘗試它時它工作正常:http://jsbin.com/pusoyej/1/edit?html, js,輸出 – Quentin

回答

0

Div屬性for-field="post-title"inputpost-titiespelling mistake

post-titlepost-titie不一樣,這就是爲什麼你的代碼沒有找到與屬性的div。

+0

它是拼寫錯誤。我很不好意思。 – Benyi

0

我正在獲取id屬性。檢查控制檯錯誤:

$(function(){ 
    $('.form textarea, :input').focus(function(){ 

    var forwhom = $(this).attr('id'); /* working */ 
    /* var forwhom = 'post-title'; works */ 

    console.log(forwhom); 
}); 

}); 

這裏是工作提琴 https://jsfiddle.net/sesn/x1ju006b/1/

0

一些提示:

1)使用Chrome瀏覽器開發工具的控制檯

2測試你的選擇)使用.prop()代替.attr()

3).closest() ins tead of $(this).parents().eq(2)

相關問題