我正在尝试将输入按钮的值设置为字符串变量。即“校车指南”;但是当 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 个类。
关于javascript - 将输入值属性设置为带空格的变量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646820/