Thursday 7 June 2018

jQuery - programmatically create dynamic links



I'm pretty new to jQuery and javaScript programming and wondered if anyone could help me?



I have slider bar which is populated using an unordered list. Works very nicely, rendering text dynamically on top of button images. Each of this list items contains a link that calls a Function. For example:



  • ';



    However I now wish to populate the entire page dynamically using and XML file. There will be no static content on the pages therefore the slider contents must be able to change and take a variable number of buttons and therefore links.
    I've retrieved the data from the XML file and stored it in a number of arrays.
    The code for adding a list item now reads as follows:



    for (i = 1; i < count; i++) {
    var newListItem = '
  • ';
    $("#sliderList").append(newListItem);
    };



    So far so good. I think. However where I'm unable to progress further is programmatically creating the link. The link opens a jQueryUI dialog box. The code for the link on the static page reads as follows:



    $('#my_link').click(function(){
    clearScreen(); //clears any open dialog boxes
    $('.myContent').dialog('open');
    return false;
    });



    My question to you is how do I create this code programmatically? The following is, I know absolutely not right and a long way off but it gives an idea of what i want to do:



    for (i = 1; i < count; i++) {
    $("'"+myLink[i]+"_link'").click(function() {
    clearScreen(); //clears any open dialog boxes
    $("'."+myContent[i]+"'").dialog.('open');
    return false;
    });
    };



    I realise also that I may be approaching this from the wrong angle, so any pointers, help, etc very much gratefully received!


    Answer



    You can attach the click handler (i.e. what you call 'link') before appending the newly created items to the DOM tree. Try modifying the block to the following:



    for (i = 1; i < count; i++) {
    var myNewContent = "."+myContent[i]; // bind myContent[i] to the closure
    var newLink = $('
    '+myTitle[i]+'
    ');
    newLink.click(function() {
    clearScreen(); //clears any open dialog boxes

    $(myNewContent).dialog('open');
    return false;
    });
    var newListItem = $('
  • ').append(
    $('
    ').append(
    '',
    newLink
    )
    );
    $("#sliderList").append(newListItem);

    };

  • No comments:

    Post a Comment

    php - file_get_contents shows unexpected output while reading a file

    I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...