在jQuery选择中合并两个var

时间:2014-02-14 05:37:55

标签: javascript jquery html

我正在尝试使用jQuery从下拉列表中获取两个选定值,并且能够成功检索这些值。问题是我无法合并检索到的内容。 Follwing就是代码。

    var selectedTemplate;

    var selectedAssignment;

    var mergeValue;

    var divContent = "<div id='" + criterion.id + "' customId='" + mergeValue + "'                style='font-weight:bold; font-style:italic;'>" + criterion.expression + "&nbsp;&nbsp;&nbsp;&nbsp;" +
                  "<a href='#' onclick=\"removeCriterion('" + criterion.id +
                  "')\"><spring:message code="form.text.criteria.remove"/></a></div>\n";


selectedTemplate   = $("#criteriaTemplate option:selected").val(); // 1st dropdown value
selectedAssignment = $("#criteriaOptions option:selected" ).val(); // 2nd dropdown value

alert("this is the Assignment value in add block: " + selectedAssignment); // success
alert("This should be the template in add block: "  + selectedTemplate);   // success

 //mergeValue = $(selectedTemplate,selectedAssignment);
 mergeValue = selectedTemplate.add(selectedAssignment); // unable able to merge the content

 alert("This is the value of the merge content in the add block: "+mergeValue); // alert is also not generated

我试图将合并内容附加到块中的customID,但是当我检查它时显示如下

<div id="8a808088442eb48001442efe70f20010" customid="undefined" style="font-weight:bold; font-style:italic;">some Text here &nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="removeCriterion('8a808088442eb48001442efe70f20010')">Remove</a></div>

建议我一些解决方案

2 个答案:

答案 0 :(得分:4)

如果要将两个值连接到一个String,请使用+运算符:

mergeValue = selectedTemplate + selectedAssignement;

结果将是:

mergeValue = "SomeTemplateSomeAssignement"

如果你想将它们都放在一个数组中,只需将它们分配给一个数组:

mergeValue = [selectedTemplate, selectedAssignement]

或者

mergeValue = [];
mergeValue.push(selectedTemplate);
mergeValue.push(selectedAssignement);

结果将是:

mergeValue = [
    "SomeTemplate",
    "SomeAssignement"
]

答案 1 :(得分:3)

你需要使用串联作为jQuery对象的selectedTemplateselectedAssignment值我觉得你要找的是将它们连接起来

mergeValue = selectedTemplate + selectedAssignment;

var selectedTemplate;

var selectedAssignment;

selectedTemplate = $("#criteriaTemplate option:selected").val(); // 1st dropdown value
selectedAssignment = $("#criteriaOptions option:selected").val(); // 2nd dropdown value

var mergeValue = selectedTemplate + selectedAssignment;

var divContent = "<div id='" + criterion.id + "' customId='" + mergeValue + "'                style='font-weight:bold; font-style:italic;'>" + criterion.expression + "&nbsp;&nbsp;&nbsp;&nbsp;" +
    "<a href='#' onclick=\"removeCriterion('" + criterion.id +
    "')\"><spring:message code="
form.text.criteria.remove "/></a></div>\n";


alert("this is the Assignment value in add block: " + selectedAssignment); // success
alert("This should be the template in add block: " + selectedTemplate); // success

alert("Merged: " + mergeValue);