在javascript中编写html时引用的问题

Issue with quotations while writing html in javascript

本文关键字:引用 问题 html javascript      更新时间:2023-09-26

我正在编写javascript中的html结构,我需要在单击链接时返回。我是这样写的

  return '<div class="contactForm">'+
'<input type="text" name="contactName" onBlur="if (this.value == "") {this.value == "Name";}" onFocus="if ((this.value == "") || (this.value == "Name")) {this.value = "";};" value="Name" style="">'+

当我在页面上看到它时,onBlur属性出现在红色颜色中,引号放错了地方。

   <input name="contactName" onblur="if (this.value == " ")="" {this.value="Name" ;}"="" onfocus="if ((this.value == " ||="" (this.value="=" "name"))="" ;};"="" value="Name" style="" type="text">

我怎么写返回部分,使我得到正确的HTML页面?我相信这是由于引号放错了地方。我在页面源中看到这个错误在期望属性名

时看到一个引号

您需要使用''':对字符串内部的引号进行双转义,一次用于字符串本身,一次用于内联JavaScript。

return '<div class="contactForm">'+
    '<input type="text" name="contactName" onBlur="if (this.value == '''"'''") {this.value == '''"Name'''";}" onFocus="if ((this.value == '''"'''") || (this.value == '''"Name'''")) {this.value = '''"'''";};" value="Name" style="">'+

如果你想让它更清晰一点,你可以使用单引号,只需要转义一次。

return '<div class="contactForm">'+
    '<input type="text" name="contactName" onBlur="if (this.value == '''') {this.value == ''Name'';}" onFocus="if ((this.value == '''') || (this.value == ''Name'')) {this.value = '''';};" value="Name" style="">'+
var element = '<div class="contactForm">';
element += '<input type="text" name="contactName" onBlur="if (this.value == '''') {this.value == ''Name'';}" onFocus="if ((this.value == '''') || (this.value == ''Name'')) {this.value = '''';};" value="Name" style="">';
element += '</div>';
return element;