2

Here is my javascript example code using jquery

$(".class").append("<a class='button-link' onclick='myFunction('"+ p1 +"' , '" + p2 + "')'>Click Me</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The result in HTML is like this

<a class="button-link" onclick="myFunction("p1' , 'p2')'></a>

But I want the result is like this

<a class="button-link" onclick="myFunction('p1' , 'p2')"></a>
2
  • Try using escaped double quotes for the onclick attr: $(".class").append("<a class='button-link' onclick=\"myFunction('"+ p1 +"' , '" + p2 + "')\">Click Me</a>"); Commented Oct 29, 2018 at 2:52
  • Ok thank you , i will try it Commented Oct 29, 2018 at 2:54

2 Answers 2

2

Try the following:

var p1 = 'p1';
var p2 = 'p2';

var myFunction = (a0,a1) => { console.log(a0, a1) }

$(".class")
    .append('<a class="button-link" onclick="myFunction(\'' + p1 + '\' , \'' + p2 + '\')">Click Me</a>');

console.log( $(".class").html() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class"></div>

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

Comments

1

Inline handlers are generally considered to be pretty poor practice and are difficult to manage, in part due to quote-escaping issues like these. Rather than using an onclick attribute, attach the handler properly using Javascript, and it should be much easier to read, debug, and think about:

const a = $("<a class='button-link'>Click Me</a>");
a.on('click', () => myFunction('p1', 'p2'));
$(".class").append(a);

const a = $("<a class='button-link'>Click Me</a>");
a.on('click', () => console.log('foo'));
$(".class").append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.