点击表单按钮后,我需要输入某个类的所有元素的所有文本 - > ' ClassOfElementOnPage txt'在表单的同一页面上变成一个名为' buildingSelections'并在使用表单提交之前使其成为隐藏字段的值。一切正常!但是有些元素是空的,即
<span class="ClassOfElementOnPage txt"></span>
我想省略迭代中的那些,只将带有文本的元素放在变量中,即
<span class="ClassOfElementOnPage txt">Text to be added to variable</span>
这是我的工作,但也收集了空元素。
//When form button is clicked go thru the page and stuff all the text into a variable and separated by a line break
$('#submitButtonID').click(function(){
var buildingSelections = "";
$('.txt.ClassOfElementOnPage').each(function(){
buildingSelections += $(this).text() + "<br>";
})
//Make the building selections hidden field value the value of the buildingSelections variable
$("#HiddenFieldinForm").val(buildingSelections);
});
感谢任何帮助!
答案 0 :(得分:4)
在循环更改中
buildingSelections += $(this).text() + "<br>";
到
var text = $(this).text();
if (text) {
buildingSelections += text + "<br>";
}