动态创建后的 jQuery 样式/引用元素

标签 jquery css

我有一个包含许多功能面板的页面 - 在其下方我为每个功能面板都包含了一个按钮。这个想法是当用户点击一个按钮时,相关的面板被渲染(其余的被隐藏)。我正在研究一些 JQuery,它...

  • 从功能面板创建一个数组 - 其中 class = slide-content
  • 遍历数组,为每个功能面板创建一个“按钮”- #slidecontrol + 唯一 ID
  • 然后将这些链接(
  • s 中的 s)附加到页面中的集合
  • 当用户单击一个链接时,代码会返回数组,关闭那些不相关的功能面板并打开相关的功能面板。然后,此代码还尝试将独特的样式应用于单击的链接....
...这就是我遇到问题的地方。出于某种原因,我无法引用以前动态创建的链接 - 既不使用 .css() 也不使用 .addClass()。

我的 jQuery 代码:

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, function (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
            }
        });
   });   

最佳答案

丹,

对运行时添加的任何元素使用 jquery live。

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

我觉得你的代码有问题

检查 $indexno 正在打印什么

 $('#slidecontent'+$indexno)

关于动态创建后的 jQuery 样式/引用元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5928895/

相关文章:

jquery - Margin Auto 渲染到 Margin 0px

html - 停止具有影响其他元素位置的相对位置的元素

jquery .position() 在 Chrome 中返回 .offset()

javascript - 使用 div 的高度来确定另一个 div 的 padding 或 margin-top

JQuery addClass 语法错误 : Unexpected token illegal

javascript - 带有无声 ajax 调用的 PayPal 快速结帐安全性

javascript - 如何修复不需要的侧滚动条?

html - 相对于其兄弟元素绝对定位一个元素

javascript - jQuery Datepicker 今天按钮不把今天的日期放在输入框中

javascript - 什么是 oncontentready 事件?