使用javascript动态打印 - 使用各种条件组件构建字符串

时间:2017-01-14 00:47:58

标签: javascript html

我需要在输入firstAuthorInitials.value.slice(0,1)之后立即删除逗号。 如果在输入firstAuthorInitials.value.slice(0,1)是写的东西,代码工作正常。

代码如下:

if (edition.value == "none") {
	div.innerHTML += 
		firstAuthorSurname.value + ", " + 
		firstAuthorName.value.slice(0, 1) + "." + 
		firstAuthorInitials.value.slice(0,1) + "." 	+ ", " +
		year.value + 
		". <i>" + title.value + "</i>. " + 
		placeOfPublication.value + ": " + 
		publisher.value + ".";

}

1 个答案:

答案 0 :(得分:0)

创建一个数组,将数据推入其中,然后加入。使用应用于每个元素的逻辑来决定是否要推送它。

&#13;
&#13;
if (edition.value == "none") {
	var stringComponents = [];

	stringComponents.push(
		firstAuthorSurname.value, 
		", ", 
		firstAuthorName.value.slice(0, 1),
		"."
	);
	
	if (/* some kind of logic */) {
		stringComponents.push(firstAuthorInitials.value.slice(0,1), "., ");
	}
	
	stringComponents.push(
		year.value + 
		". <i>",
		title.value,
		"</i>. ",
		placeOfPublication.value,
		": ",
		publisher.value,
		"."
	);
	
	div.innerHTML += stringComponents.join("");
}
&#13;
&#13;
&#13;