将Input Value属性设置为带有空格的变量

Setting the Input Value attribute to a variable with space.

本文关键字:空格 变量 Input Value 属性 设置      更新时间:2023-09-26

我试图将输入按钮的值设置为字符串变量。e《校车指南》;但是当HTML加载时,按钮中只会出现第一个单词。我的代码如下所示。谢谢你的帮助。

var title="A Guide to the School Bus";
var htmlString= "<div class="+title+ ">"+"<input type="+"button  "+"value="+title+"  onclick=loadBook()>"+"</div>";
$(htmlString).appendTo(attachPoint);

附件点是HTML中的一个引用,我使用以下方法得到。

var attachpoint=document.querySelector('.buttonAttachPoint');

问题在于您没有在属性值周围加上引号。试试这个:

var htmlString= '<div class="'+title+'"><input type="button" value="'+title+'"  onclick="loadBook()"></div>';

您可以转义字符串中的所有",或者像我所做的那样,在'"之间切换。"将显示为正常字符,'用于标记字符串的开始和结束。

作为一个侧面点,你可能不想把变量title作为class放在div上,因为它会将每个单独的单词作为一个类添加,所以在你的例子中,div将有6个类添加到它。