我正在尝试使用jQuery从逗号分隔的字符串创建HTML元素(Div)。
假设我有一个字符串,看起来如下:
options ="some texts, another text, some more text";
我需要创造这样的东西:
<div>some texts</div>
<div>another text</div>
<div>some more text</div>
我首先拆分逗号分隔的字符串如下:
var str = options;
var temp = new Array();
temp = str.split(", ");
然后我需要在这个函数之后创建div,我不知道怎么做。
有人能给我个建议吗?
发布于 2016-06-16 01:04:51
试试这个:
var options ="some texts, another text, some more text";
var temp = options.split(", "); // first split string and convert it to array
var str = '';
$.each(temp, function(i,v) { // loop through array
str += "<div>"+v+"</div>"; // create html string and store it in str variable
});
$("body").append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
发布于 2016-06-16 01:05:26
您可以使用jQuery进行类似的操作。
var options = "some texts, another text, some more text";
var temp = options.split(", ");
// iterate and generate array of jQuery elements
var divs = temp.map(function(txt) {
// generate div using jQuery with text content as array element
return $('<div/>', {
text: txt
})
})
// update html content, use `append()` if you want to append instead of replacing entire content
$('body').html(divs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
发布于 2016-06-16 01:09:07
您不需要转换为数组--只需将逗号和相关空格替换为结束div和开始div标记,然后添加一个开头的开始和结束一个结束的空格,就可以得到html结构。
var options ="some texts, another text, some more text";
var temp = "<div>" + options.replace(/, /g,"</div><div>") + "</div>;
//this will give: <div>some texts</div><div>another text</div><div>some more text</div>
$("body").append(temp);
https://stackoverflow.com/questions/37854554
复制相似问题