最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript string parameter in function - Stack Overflow

programmeradmin7浏览0评论

I'm working with google maps api and I want the label of a marker have a link that execute a warning.

var str = "hi";
var mp_position = createGoogleMapsLocation(data[i].location);
var text = "<p>Edit: <a href=# onClick='edit("+str+")'>Click here</a></p>";
addMeetingMarker(mp_position, text);

The addMeetingMarker function works, but edit function not. The code is:

function edit(message) {
    alert(message);
}

If you set an integer in the argument of the edit function it works, but passing the variable str does not work. Why?

I'm working with google maps api and I want the label of a marker have a link that execute a warning.

var str = "hi";
var mp_position = createGoogleMapsLocation(data[i].location);
var text = "<p>Edit: <a href=# onClick='edit("+str+")'>Click here</a></p>";
addMeetingMarker(mp_position, text);

The addMeetingMarker function works, but edit function not. The code is:

function edit(message) {
    alert(message);
}

If you set an integer in the argument of the edit function it works, but passing the variable str does not work. Why?

Share Improve this question asked Jul 5, 2012 at 20:08 Josh MouseJosh Mouse 2071 gold badge3 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You need more double quotes to surround your value string - so:

var text = "<p>Edit: <a href=# onClick='edit("+str+")'>Click here</a></p>";

bees

var text = "<p>Edit: <a href=# onClick='edit(\""+str+"\")'>Click here</a></p>";
edit("+str+")

will result in the javascript code

edit(hi)

Where hi is an unknown variable. Depending on what you want the edit function to do, either add a quote: edit\""+str+"\"), or remove the plusses: edit(str). In the last case, the edit function will receive the str variable, in the first case, it will receive the "hi" literal.

You're missing the double quotes necessary to make str a quoted string.

发布评论

评论列表(0)

  1. 暂无评论