简体   繁体   中英

Escape Javascript String

As part of a div overlay, I have written some code to make a button. This function accepts an Object

    function f1(marker){
    var notesBox = '<div id="saveMarkerNotesDiv'+marker.id+'"> <input type="button" onclick="saveMarkerNotes(\''+ marker+'\')" id="saveMarkerNotes'+marker.id+'" value="Save" /> </div>';
return notesBox;
    }

function saveMarkerNotes(marker){
 alert(marker);
//Just shows [object Object]
alert(marker.id);
//Above line throws an error as it cannot find id in the **string marker**. 
}

Question is why is turning into a string when I have escaped it. Also i used the same object in the previous method f1 and there it works fine. When the above f1 function is called, it has the object marker. I can access the attributes and properties of marker in the method.

The above function f1 has the marker object. However when the function saveMarkerNotes() is called, it does not seem to have the object anymore. When I print marker.id in saveMarkerNotes() it shows undefined and when I show the marker object in the alert it shows up as [object Object]. I feel that the marker object is turning into a string and does not remain an object anymore in the onclick="saveMarkerNotes(\\''+ marker+'\\')" code. How can I escape the string so that it remains an object and not a string.

Use the DOM API to generate DOM elements ( <div> s etc.) and attach event handlers to them programmatically using Javascript. Don't go through concatenating strings which will be interpreted as HTML which attaches elements to the DOM which eventually triggers Javascript again from strings.

let input = document.createElement('input');
input.type = 'button';
input.id = 'saveMarkerNotes' + marker.id;
input.value = 'Save';
input.addEventListener('click', saveMarkerNotesDiv.bind(null, marker));

let div = document.createElement('div');
div.id = 'saveMarkerNotesDiv' + marker.id;
div.appendChild(input);

return div;

You now need to .appendChild(div) to some element to add it to your page. Yes, this may seem more verbose and annoying, but it is the correct way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM