开发者

jQuery styling/referencing an element after its dynamic creation

开发者 https://www.devze.com 2023-03-03 14:46 出处:网络
I have a page with a number of feature panels - beneath which I include a button for each of them. The idea is that when the user clicks on a button, the relevant panel is rendered(with the rest being

I have a page with a number of feature panels - beneath which I include a button for each of them. The idea is that when the user clicks on a button, the relevant panel is rendered (with the rest being hidden). I'm working on some JQuery which...

  • creates an array from the feature panels - where class = slide-content
  • steps through the array, creating a 'button' for each feature panel - #slidecontrol + unique ID
  • these link (s within
  • s) are then appended to a set within the page
  • when the user clicks a link, the code steps back through the array, turning off those feature panels that arent relevant and turning on the one that is. This code then also attempts to apply a unique style to the link that was clicked on....
... which is where I'm hitting a problem. For some reason I can't reference the previously dynamically created links - Neither using .css() nor .addClass().

My jQuery code:

slideArray = $('.slide-content'); //array of slide-content divs
var $ulslidecontrols = $('#slide-controls'); //instance of slides ul
var $indexno 
//step through the array - create a nav button/link for each slide content div
$.each(slideArray, function (index, value) {
    $indexno = index;
    $indexno++;
    $ulslidecontrols.append(
        $("<li><a href='#' class='slide-control' id='slidecontrol " + $indexno + "'>"
        + $indexno + "</a></li>")
    );
});

$('a.slide-control').click(function () {
    var $slide = $(this).attr("id");
    $slide = $slide.charAt($slide.length - 1);

    //step through the slideArray, hiding slide-content not selected and amending
    style of slide-controls
        $.each(slideArray, func开发者_如何学Ction (index, value) {
            $indexno = index;
            $indexno++
            if ($indexno == $slide) {
                $('#slidecontent' + $indexno).hide().fadeIn(600); 
                //display slide content
                $('#slidecontrol' + $indexno).css('font-size', '50px');
            } 

            else {
                $('#slidecontent' + $indexno).hide(); //hide slide content
            }
        });
   });   


Dan,

use jquery live for any elements added at runtime.

http://api.jquery.com/live/

i think something wrong here in your code

check what is $indexno is printing and

 $('#slidecontent'+$indexno)
0

精彩评论

暂无评论...
验证码 换一张
取 消