2013-05-02 56 views
0

通過下面是函數如何獲得變量通過功能的JavaScript/jQuery的

function addCategory(category) { 
$('#category_choice').append($('#!the variable "category" has to go in here!')); 
$('#feed_submit_categories').hide(); 
} 

的「類別」變量發送帶有被附加的元素的ID。我如何將「類別」var插入到函數中?在PHP中,使用$ var_name標籤要容易得多......但在這裏,我不知道如何包含它。

+1

你要找的字符串連接。 – SLaks 2013-05-02 18:06:30

回答

3
function addCategory(category) { 
    $('#category_choice').append($('#'+category)); 
    $('#feed_submit_categories').hide(); 
} 
級聯的

簡單實例(變量,字符串):

var h = "Hello"; 
var w = "World!"; 

alert(h+w);   // HelloWorld! 
alert(h+' '+w);   // Hello World! 
alert(h+' my dear '+w); // Hello my dear World! 

jQuery選擇可以使用string字面上表示元件ID選擇:

$('#element') 

這意味着你保持作爲串你需要什麼和你連接一個變量:

var elName = "element"; // string variable 
$('#'+ elName) // same as: $('#element') 

如果您需要在每次追加新的新鮮元素不喜歡:

$('#category_choice').append('<div id="'+category+'" />'); 

只要確保不重複的元素ID的ID必須爲每個頁面元素的獨特。

+1

謝謝! *隨機文本覆蓋評論框中的最小字符* – 2013-05-02 18:10:44

+1

thanx a million!我這樣做(但無法通過「類別」項目),但我決定只複製我想追加的div,但它開始消耗它們=) – 2013-05-02 18:28:02

+0

@KrisRimar歡迎您!快樂編碼 – 2013-05-02 18:29:02

2
$('#category_choice').append($('#'+category)); 

jQuery選擇器只是被評估的字符串,您可以根據基本的Javascript規則生成一個字符串。

例如:

var iAmString = "#"+category; 
$(iAmString) //<-- using string var as a selector 
+0

有沒有辦法制作我正在追加的div的副本?因爲我使用PHP回顯類別,並且每次運行此功能時,它都會帶走分區... – 2013-05-02 18:22:42

2

使用

function addCategory(category) { 
    $('#category_choice').append($('#'+category)); 
    $('#feed_submit_categories').hide(); 
} 
+0

謝謝! *隨機文本覆蓋評論框中的最小字符* – 2013-05-02 18:11:24