简体   繁体   English

转义Javascript字符串

[英]Escape Javascript String

As part of a div overlay, I have written some code to make a button. 作为div覆盖的一部分,我编写了一些代码来制作按钮。 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. 另外我在以前的方法f1中使用了相同的对象,并且在这里工作正常。 When the above f1 function is called, it has the object marker. 调用上述f1函数时,它具有对象标记。 I can access the attributes and properties of marker in the method. 我可以在方法中访问标记的属性和属性。

The above function f1 has the marker object. 上面的函数f1具有标记对象。 However when the function saveMarkerNotes() is called, it does not seem to have the object anymore. 但是,当调用函数saveMarkerNotes()时,似乎不再具有该对象。 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]. 当我在saveMarkerNotes()中打印marker.id时,它显示未定义,而当我在警报中显示标记对象时,它显示为[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. 我觉得在onclick =“ saveMarkerNotes(\\''+ marker +'\\')”代码中,标记对象正在变成字符串,不再是对象。 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. 使用DOM API生成DOM元素( <div>等),并使用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. 不要经历将字符串解释为HTML的串联字符串,HTML会将元素附加到DOM,而DOM最终会再次从字符串触发Javascript。

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. 现在,您需要将.appendChild(div)添加到某个元素,以将其添加到页面中。 Yes, this may seem more verbose and annoying, but it is the correct way to do it. 是的,这似乎更加冗长和烦人,但这是正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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