Reputation: 999
I'm aware there are plenty of similar questions here, and even one of my own touches on this in a way - but I'm struggling with this particular code, and as a JS newbie, I can't figure out where I'm going wrong with it.
I'm basically adapting TinyMCE to get rid of the popup dialogs (replacing them with my own, to keep it clean). The one I'm working on right now is inserting images. Here's my function as it is now;
<script type="text/javascript">
function addImage(imgurl){
tinyMCE.execCommand('mceInsertContent',false,'<img src=" +imgurl+ " style="float:left; margin: 0 5px 5px 0;" />');
}
</script>
And the link
<a href="javascript:;" onclick="addImage('/myimage.jpg');return false;">[Insert Image]</a>
The function 'works' in that it inserts the code, but the 'imgurl' (myimage.jpg, in this example) isn't being passed - instead of /myimage.jpg being inserted, its inserting +imgurl+.
Pointers much appreciated from this newbie!
Upvotes: 1
Views: 159
Reputation: 10057
Your concatenation isn't right... When opening with single quotes, concat with single quotes. When with double quotes, use double quotes.
function addImage(imgurl){
tinyMCE.execCommand('mceInsertContent',false,'<img src="'+imgurl+'" style="float:left; margin: 0 5px 5px 0;" />');
}
You can find tons of easy tutorials that explain concatenation in-depth. The general rule is to be consistent. If you wrap your string around double quotes, single quotes won't stop the parsing of a string because the compiler recognized double quotes to do this. The same goes with single quotes. The code below will parse Hello'; // broken string
as the string just as concatenating using the wrong quote will also.
var string = "Hello'; // broken string
A good way to avoid problems like these (because even expert programmers still get syntax errors every once in a while) is to use a good programming editor (notepad++, sublime 2, coda, textmate, phpad) that has syntax highlighting. Even the simple highlighter that stackoverflow.com has is sufficient. Just by looking at the code above, you can tell that everything after the double quote ("
) is still parsed as a string as it is still the same color as the string, while a variable would change colors when put through a syntax highlighter.
Upvotes: 3
Reputation: 96845
Your string isn't formatted correctly:
'<img src="' + imgurl + '" style="float:left margin: 0 5px 5px 0;" />';
Upvotes: 0
Reputation: 91349
You're passing the variable just fine. The problem is that are you are not concatenating its value, but a string with the value +imgurl+
. Use the following instead (note the closing and starting '
just before and after + imgurl +
:
tinyMCE.execCommand('mceInsertContent',false,'<img src="' +imgurl+ '" style="float:left; margin: 0 5px 5px 0;" />');
Upvotes: 1