0

这是功能

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

“类别”变量发送必须附加的元素的 id。如何将“类别”变量插入函数?在 PHP 中,使用 $var_name 标记要容易得多……但是在这里,我不知道如何包含它。

4

3 回答 3

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 必须是每个页面元素唯一的。

于 2013-05-02T18:06:03.253 回答
2
$('#category_choice').append($('#'+category));

jQuery 选择器只是被评估的字符串,您可以按照基本的 Javascript 规则生成字符串。

例如 :

var iAmString = "#"+category;
$(iAmString)  //<-- using string var as a selector
于 2013-05-02T18:06:31.993 回答
2

采用

function addCategory(category) {
  $('#category_choice').append( $('#'+category) );
  $('#feed_submit_categories').hide();
}
于 2013-05-02T18:09:19.630 回答