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.
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.
Share Improve this question asked May 7, 2016 at 14:15 Damian ZiołeckiDamian Ziołecki 71 silver badge3 bronze badges 5- 1 "This code doesn't work properly." is not a sufficient problem description. – PeeHaa Commented May 7, 2016 at 14:17
-
5
Don't you see the problem with this portion of your code?
onclick='test('test')'
– Dexygen Commented May 7, 2016 at 14:18 - Take a look at your pages generated HTML and you will see the issue – Adjit Commented May 7, 2016 at 14:19
- Possible duplicate of Event binding on dynamically created elements? – trenthaynes Commented May 7, 2016 at 14:20
- This is not a duplicate, it's malformed HTML – Dexygen Commented May 7, 2016 at 14:21
5 Answers
Reset to default 4You 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
As alluded to in the ments, 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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
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');
});
Use ` quote instead of '
I created a jsbin here. II hope this is what you are trying to do
http://jsbin./wicanok/edit?html,js,output
$('#element').append("<a onclick='test(`test`)'> <i class='fa fa-spin fa-pencil' aria-hidden='true'>Hi</i></a>");
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!
});