MR. A
MR. A

Reputation: 195

How do I print the original string for JavaScript function

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>

Upvotes: 2

Views: 139

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370789

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>

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30360

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>

Upvotes: 2

Related Questions