-4

I have problem with append function. This code doesn't work properly.

$(element).append("<a onclick='test('test')'> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i></a>");

test function:

function test(value)
{
 alert(value);
}

I suspect that the problem is related to onclick function.

5 Answers5

4

You have to escape apostrophes inside:

 $(element).append("<a onclick='test(\"test\")'> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i></a>");

And make sure test() is defined globally (and not inside document ready for example).

Here is an example:

window.test = function(value){
 alert(value);
};
$('div').append("<a onclick='test(\"test\")'>click me</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
skobaljic
  • 9,379
  • 1
  • 25
  • 51
2

As alluded to in the comments, you can't nest similar quote marks in a string like you are currently doing. You need to escape them with a back slash:

function test(value) {
 alert(value);
}

var element = $('body');

$(element).append("<a onclick='test(\"test\")'> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i>Click Me</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Turnip
  • 35,836
  • 15
  • 89
  • 111
2

You're better off taking that inline JS out altogether and using jQuery to add the event listener (using event delegation because you're adding new elements to the DOM).

$(element).append('<a class="test">...');

$(document).on('click', '.test', function () {
  test('test');
});
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Use ` quote instead of '

I created a jsbin here. II hope this is what you are trying to do

http://jsbin.com/wicanok/edit?html,js,output

$('#element').append("<a onclick='test(`test`)'> <i class='fa fa-spin fa-pencil' aria-hidden='true'>Hi</i></a>");
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

You can try this:

$(element).append("<a onclick='test('test')' class="your_class"> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i></a>");
$(document).on('click',".your_class", function(){
//Write here your code!
});
Costas Bakoulias
  • 895
  • 9
  • 11