【问题标题】:Is is possible to pass a selector as a function parameter in Javascript?是否可以在 Javascript 中将选择器作为函数参数传递?
【发布时间】:2014-05-26 01:09:31
【问题描述】:

我正在尝试为特定应用程序开发一种幻灯片。我在要显示的 div 的增量方面遇到了一些问题。 我需要传递选择器及其位置,然后增加它的位置。

检查我需要做什么的代码:

HTML:

    <div name="div-default" class="title-result">
        <?php
            echo "$name";
        ?>
    </div>
    <div name="div01" id="div01" class="title-result">
        <?php
            echo "Seu número de Personalidade é: $numerologia[0]";
        ?>
    </div>
    <div name="div02" class="title-result">
        <?php
            echo "Seu número de Destino é: $numerologia[1]";
        ?>
    </div>
    <div name="div03" class="title-result">
        <?php
            echo "Seu número de Lição de Vida é: $numerologia[2]";
        ?>
    </div>

    <div>
        <button onclick="mudarDivNext([name ^= div0]:nth-child(SEND_ITS_POSITION_HERE))" id="next" class="change-div"></button>
     </div>

CSS:

 //here i define that the first div is visible, and the next ones invisible
    div[name ^= div0]:nth-child(2){
        display: inherit;
    }

    div[name ^= div0]{
        display: none;
    }

Javascript:

//This script already works for a fix position (from 2 for 3, for example) - need to make it work for all the divs.
function mudarDivNext(){
    var n = 2;
    $("[name ^= div0]:nth-child("+n+")").css("display", "none");
    $("[name ^= div0]:nth-child("+(n+1)+")").css("display", "inherit");
}

【问题讨论】:

  • 是的,有可能,你试过了吗?
  • 是的,我做到了.. 它在这里不起作用。我不知道如何发送我的 div 位置的编号 ([name ^= div0]:nth-child(2);[name ^= div0]:nth-child(3); [name ^= div0] :nth-child(4))...

标签: javascript css jquery-selectors css-selectors selector


【解决方案1】:

两件事,在使用内联函数调用时不要忘记引号,并使用字符串连接来发送参数:

mudarDivNext("[name ^= div0]:nth-child(" + variable + ")")

【讨论】:

  • 感谢您的回答,但是如何在我的 HTML 代码中定义变量的值? :( 我需要得到我的 div 的位置,我还不能这样做。
  • 嗯...位置基于什么?我也相信你应该把它扔到它自己的按钮处理程序中,这样你就可以使用this 的实例来追踪 div 的索引并使用它。
【解决方案2】:

不如给可见元素添加一个类,让jQuery在点击时选择下一个元素来获取该类:

<div name="div-default" class="title-result active">
        <?php
            echo "$name";
        ?>
    </div>



<script>
    jQuery(document).ready(function() { 
                (function ($) { 

            $('#next').on('click',function(){

                $('.active').removeClass('active').next().addClass('active');


            });

        })(jQuery);
    });
</script>

然后添加 css 以仅显示具有“活动”类的 div。

<style>
.title-result{display:none;}
.title-result.active{display:block;/*or whatever*/}
</style>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-07
    • 2014-04-15
    • 2020-02-19
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多