我在Javascript中输入以下内容:["1213381233", "1213551233", "1213551255"]
,我需要加入它们并设置其格式。看下面的例子:
<div id="segment_form">
<button id="add_condition">
Click me
</button>
</div>
var data_field = 'asset_locations_name';
var data_condition = 'in';
var data_values = ["1213381233", "1213551233", "1213551255"];
$("#segment_form").on('click', '#add_condition', function() {
var li = '';
var has_parenthesis = false;
if (data_condition == 'in' || data_condition == 'not in' || data_condition == 'between' || data_condition == 'not between') {
has_parenthesis = true;
}
if (data_values instanceof Array && data_values.length >= 1) {
li += '<li data-field="' + data_field + '" data-condition="' + data_condition + '">';
li += data_field + ' ' + data_condition;
if (has_parenthesis) {
li += '( ';
}
$.each(data_values, function(index, value) {
li += '<span title="Click to remove this item from the list" data-id="' + value + '">' + value + '</span>';
});
if (has_parenthesis) {
li += ' )';
}
li += '</li>';
}
$('body').append(li);
});
这个想法是具有以下输出:
asset_locations_name in (1213381233,1213551233,1213551255)
我的代码几乎可以正常工作,但是我得到了:
asset_locations_name in( 121338123312135512331213551255 )
这里的诀窍是我不能执行
data_values.join()
,因为我需要将每个值添加为span本身上的data-id
属性。还有其他清洁解决方案吗?欢迎任何帮助!
我忘了提起小提琴here。
最佳答案
那这个呢?
var data_field = 'asset_locations_name';
var data_condition = 'in';
var data_values = ["1213381233", "1213551233", "1213551255"];
$("#segment_form").on('click', '#add_condition', function() {
var li = '';
var has_parenthesis = false;
if (data_condition == 'in' || data_condition == 'not in' || data_condition == 'between' || data_condition == 'not between') {
has_parenthesis = true;
}
if (data_values instanceof Array && data_values.length >= 1) {
li += '<li data-field="' + data_field + '" data-condition="' + data_condition + '">';
li += data_field + ' ' + data_condition;
if (has_parenthesis) {
li += '(';
}
$.each(data_values, function(index, value) {
// Note the 'prefix' variable here
var prefix = (index == 0) ? '' : ', ';
li += '<span title="Click to remove this item from the list" data-id="' + value + '">' + prefix + value + '</span>';
});
if (has_parenthesis) {
li += ')';
}
li += '</li>';
}
console.log('data_field =>', data_field, 'data_condition => ', data_condition, 'data_values =>', data_values, 'li =>', li);
$('body').append(li);
});
我用解决方案创建了一个new fiddle。