简体   繁体   中英

How to call function on hyperlink text click

How can I call this *on_search* function by clicking on the text (item.name)?

$.each(docs, function(i, item) {
            $('#body').append($('<div><a href="">' + item.name </a></div><br/>'));
       });

// call this function whenever user clicks the text
function on_search() {            
     var url ='http:myhomepage/select/?wt=json&json.wrf=?&q='+item.name;
     $.getJSON(url, on_text);
    }

Give a class set at event handler to it.

   $.each(docs, function(i, item) {
                $('#body').append($('<div><a href="" class="my-anchor">' + item.name </a></div><br/>'));
    $(".my-anchor").click(on_search);
           });

    // call this function whenever user clicks the text
    function on_search() {            
         var url ='http:myhomepage/select/?wt=json&json.wrf=?&q='+item.name;
         $.getJSON(url, on_text);
        }

Not sure if each link needs to be wrapped inside its own div. In fact, to make this work well, you may want to put all of these links inside a particular div.

From there, here's what you do:

$('#divName').find('a').click(function (event) {
    var url=...
    event.preventDefault(); // Stops the browser from actually following the link
    [...]
});

if you add an id or a class you can the just add

   $('.yourClass').click(function()
    {
        var x = $(this).attr('href');
        on_search();
        // you would probably want to pass the item name as a parameter: on_search(x);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM