-1

I´d like to prepend a div with an onClick function via jQuery like that:

var myFirstDivChange = '<div class="myClass" onClick="changemyvariable('4v5');">MyText</div>', $('#myDiv').prepend(myFirstDivChange); 

This is the changemyvariable function:

function changemyvariable (mynewvariable) { var myoldvariable = mynewvariable } 

It does not work and returns

SyntaxError: syntax error changemyvariable( 

Is there a problem with " or ' ? If i try it like "4v5" it does not work either..

3
  • you have ' within '. Commented Dec 10, 2013 at 21:23
  • You need to escape the internal single quotes here as changemyvariable(\'4v5\') but really you ought to be binding that event dynamically rather than coding it into the markup. Commented Dec 10, 2013 at 21:23
  • Conside using .click() to bind the event rather than hard-coding it. Commented Dec 10, 2013 at 21:25

2 Answers 2

2

You have to quote the single-quotes in your HTML string:

var myFirstDivChange = '<div class="myClass" onClick="changemyvariable(\'4v5\');">MyText</div>', 

You'd be better off adding with jQuery, since you're using the library anyway:

$('#mydiv').prepend($('<div/>', { text: "MyText" , "class": "myClass" , click: function() { changemyvariable("4v5"); } })); 

Same effect, but less messy.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to escape the quotes

'<div class="myClass" onClick="changemyvariable(\'4v5\');">MyText</div>' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.