Crumblenautjs Crumblenautjs - 1 year ago 73
Ajax Question

Changing a child span to a link which calls a function

I have an AJAX function which populates a

with spans of data into a template. I would like to append these spans to links, which when clicked call a function. With what I do have, it does seem an href link is getting added, but the text itself is still not clickable.

Here's the html from the IDE as well as from the developer tools in IE :

<div id="subtotal_menu">

page view
Developer tools IE
Here's what I have tried so far:

var $menu = $('#subtotal_menu');

Also tried to create a separate function to operate on the DOM element:

function createVendorInvoiceLinks() {
var subTotalmenu = document.getElementById("#subtotal_menu").find("span");
var aTag = document.createElement('a');
aTag.setAttribute('href', "myfunction()");

Answer Source

This could help you:

var $menu = $('#subtotal_menu');
$menu.find("span").append('<a href="javascript:void(0)">Link</a>');
// append an anchor to the span inside #subtotal_menu
// set javascript:void(0) as href to avoid unwanted behaviour on click

$('#subtotal_menu').on('click', 'a',function(){
    // do whatever myfunction() does
//set up a proper event handler and use event-delegation to cope with 
//dynamic added element from e.g. your mentioned ajax-request

When you want the whole span to be clickable just change the binding from the event handler from a to span. This way you don't event need to append an anchor.



jQuery .append()

event delegation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download