I have added a new element via jquery. Now I want a function to trigger when the element is clicked. I know there are many answers to this, but they don’t seem to work for me. Not sure what I am doing wrong here.
I have tried:
new_ele = "<a>click me</a>"
new_ele.click(function() {alert('xxxx');});
other_ele.append(new_ele);
This fails before the new_ele is appended.
I have also tried (instead of the second line above)
new_ele.onclick = function() { alert('blah'); };
This appends the element, but nothing happens when I click.
And
new_ele.on('click',function() {alert('ddd');});
This also fails before the element is appended.
Change it to:
In order to add a jQuery
.click()handler, you need a jQuery object that you can call the.click()method on. Your code was trying to do:which obviously wouldn’t work because there’s no click method on a string. Instead, you need to turn that HTML string into an actual jQuery object by calling
$()on it.