2017-05-25 13 views
1

我得到一個錯誤,我想知道爲什麼,但不知道如何解決它....例如我的標籤/ ID是:了jQuery找出標籤屬性未工作

shipping_address[country] << i think because of the brackets []

和我的JS是

$(document).ready(function() { 
    $("form :input").each(function(index, elem) {   
     var eId = $(elem).attr("id"); 
     var label = null; 
     if (eId && (label = $(elem).parents("form").find("label[for="+eId+"]")).length == 1) { 
      $(elem).attr("placeholder", $(label).html()); 
      $(label).remove(); 
     } 
    }); 
}); 

錯誤:

js__jquery.js?1419646…:1468 Uncaught Error: Syntax error, unrecognized expression: label[for=billing_address[first_name]]

示例HTML:

<div class="col-sm-6"> 
    <div class="form-group"> 
     <label for="card[first_name]">First Name<span> *  </span></label> 

     <input id="card[first_name]" name="card[first_name]" type="text" class="form-control" value="" validate="true"> 
    </div> 
</div> 
+2

請問您可以添加html代碼。 –

+0

你需要在屬性選擇器內部轉義'['和']'。 – Barmar

+0

對不起,添加了HTML和新的JS,所以對我來說試錯:) –

回答

5

將屬性值包裹在引號或轉義元字符中,因爲id值包含一些在jQuery中有特殊含義的元字符。

.find("label[for='" + eId + "']") 
//    -^-----------^- 


jQuery docs

To use any of the meta-characters (such as !"#$%&'()*+,./:;<=>[email protected][]^`{|}~) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.


FYI:使用text()方法,而不是html()方法來獲取文本內容。

$(elem).attr("placeholder", $(label).text()); 
//        ------^^^^^^--- 
+1

工作了一種享受!其添加在 html - 只是看看如何解決現在:) –

+0

.text而不是.text :)感謝您的幫助隊友 –

+0

在我從HTML轉換爲文本之前,有一種方法可以從跨度中刪除空格,因爲它目前像 *,並且很好的清理,因此 *然後以文本形式輸出。 。 感謝你的幫助。 –

1

屬性選擇器中的方括號需要轉義。

var eId = elem.id.replace(/[\[\]]/g, '\\$&'); 
+0

或' var eId = elem.id.replace(/ \ [| \]/g,'\\ $ &');' –