문제

I am writing a html structure in javascript that I need to return when a link is clicked.I have it like this

  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="">'+

When I see it on the page the onBlur attribute appears in red color and the quotes are misplaced .I see it like this on the page.

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

How can I write the return portion so that I get it right in the HTML page?I believe it is due to quotes getting misplaced.I see this error in the page source saw a quote when expecting an attribute name

도움이 되었습니까?

해결책

You need to double-escape the quotes inside the string with \\\: once for the string itself and once for the inline 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="">'+

If you want to make it a bit more legible you can use single quotes that need to be escaped only once.

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top