我希望有人能帮助我解决这个问题...我按照这里的教程进行操作:http://jsbin.com/hehurot/5/edit?html,css,js,console,output在包含标签的 HTML 表单上创建一个字段。现在,当我单击表单上的“提交”时,我想使用标签获取该字段中的数据并对其执行某些操作(保存到数据库)。
由于每个标签都是一个,我将如何从字段中获取数据?
这是我当前的标签字段代码:
<div class="form-group">
<label class="col-sm-3 control-label">Equipment</label>
<div id="tags" class="col-sm-9">
<span>Hardhat</span>
<span>Steel Toe Boots</span>
<input id="equipment" type="text" name="equipment" value="" placeholder="Add equipment" >
</div>
</div>
使标签字段起作用的 JS(CSS 可在上面的链接中找到)
<script type="text/javascript">
$(function(){
$("#tags input").on({
focusout : function() {
var txt= this.value.replace(/[^a-z0-9\+\-\.\#]/ig,'');
if(txt) $("<span/>",{text:txt.toLowerCase(), insertBefore:this});
this.value="";
},
keyup : function(ev) {
if(/(188|13)/.test(ev.which)) $(this).focusout();
}
});
$('#tags').on('click', 'span', function() {
/*if(confirm("Remove "+ $(this).text() +"?")) */$(this).remove();
});
});
</script>
现在在我的 JS 文件中,如何将值保存为单独的?
我尝试了以下方法,但这不起作用,返回空字符串:
'equipment': $('#tags').val()
预先感谢您的帮助!
最佳答案
试试这个:
var tags = $('#tags span').map(function () {
return $(this).text();
});
后续:
I modified it a bit to save all the values from the to a comma separated list.
var tags = $('#tags span').map(function () {
return $(this).text();
});
tags = Array.prototype.join.call(tags, ",");
console.log(tags);
Followup question, in Javascript how can I add a tag programatically? I want to loop through the comma separated list and add each value back to tags.
$('#tags').append(tags.split(",").map(function (tag) {
return "<span>" + tag + "</span>";
}));
关于javascript - 在 HTML/JavaScript 中获取多个 <span> 标签的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089631/