【问题标题】:Pass dynamic id value jquery div jump to function传动态id值jquery div跳转到函数
【发布时间】:2014-02-02 19:58:17
【问题描述】:

我卡在 jquery div 跳转到问题上。问题是我正在创建动态 <a href="" id="1_1"></a> 和动态 div 也说 <div id="1_1_div"></div> 我正在使用以下 jquery 函数滚动到特定的 div

<script>
        $(document).ready(function (){
            $("#click").click(function (){
                alert ("test");
                //$(this).animate(function(){
                    $('html, body').animate({
                        scrollTop: $("#div1").offset().top
                    }, 1000);
                //});
            });
        });
    </script>

我的问题是如何将动态 id 传递给 $("") 任何帮助将不胜感激。

【问题讨论】:

  • 字符串连接:$("#" + this.id + "_div").offset().top
  • 我明白了,但问题是当我们有很多&lt;a href="#" id="1_1"&gt;Div1&lt;/a&gt; &lt;a href="#" id="1_2"&gt;Div2&lt;/a&gt;时如何调用函数

标签: javascript jquery


【解决方案1】:
$(document).ready(function (){
        $(".click").click(function (){
            alert ("test");
            var divID = '#' + $(this).attr('id') + '_div';
                $('html, body').animate({
                    scrollTop: $(divID).offset().top
                }, 1000);
        });
    });

并添加&lt;a class="click" ...

【讨论】:

  • 请在上面的评论中解决我的问题。我想将 &lt;a&gt;&lt;/a&gt; 的动态 id 传递给 #click 以便点击它会滚动到该 div
【解决方案2】:

字符串连接:

$("#" + this.id + "_div").offset().top

请注意,不需要创建唯一的 ID,DOM 具有树状结构,为遍历和选择目标元素提供了许多不同的方法。

由于您是动态生成元素,因此您还应该委托事件,您可以向元素添加类并使用on 方法:

$('#aStaticParentElement').on('click', '.anchors', function() {
   // TODO:
   // select the target element either by traversing 
   // or by using an identifier
});

【讨论】:

    【解决方案3】:

    Visualize it here

    首先,由于您有多个链接,请使用一个类对它们进行分组:

    HTML

    <a href="#" id="1_1" class="click">Click me 1_1</a>
    <a href="#" id="1_2" class="click">Click me 1_2</a>    
    <a href="#" id="1_3" class="click">Click me 1_3</a>
    

    jQuery

    ​​>
    $(document).on('click', '.click', function (e) {
        var theID = $(this).attr('id');
        $('html, body').animate({
            scrollTop: $('#' + theID + '_div').offset().top
        }, 1000);
        return false;
    });
    

    我这样做的前提是您正在动态创建这些链接(因此是委托)。如果它们是静态的并且在页面加载期间不会改变,您可以使用$('.click').click(function()... 而不是$(document).on('click', '.click', function()...

    【讨论】:

    • 感谢您的可视化 +1 :)
    【解决方案4】:

    用户此行

    $("#" + $(this).attr("id") + "_div").offset().top
    

    ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多