【问题标题】:Javascript issue when adding a second script to the page向页面添加第二个脚本时出现 Javascript 问题
【发布时间】:2017-02-24 04:32:25
【问题描述】:

两个 JS 脚本都有效。我的问题是,当我添加第二个 JS 脚本时,第一个 JS 不起作用。我该如何解决这个问题?

第一个 JS 脚本

<script>
$(document).ready(function(){
    $("button1").click(function(){
        $("div1").toggleClass("grid");
    });
});
</script>

第二个 JS 脚本

 <script>
var $j = jQuery.noConflict();
$j(document).ready(function () {
    $j("#trigger").change(function () {
        if ($j(this).data('options') == undefined) {
            $j(this).data('options', $j('select.switchable option').clone());
        }
        var id = $j(this).val();
        var that = this;
        $j("select.switchable").each(function () {
            var thisname = $j(this).attr('name');
            var theseoptions = $j(that).data('options').filter('.' + thisname + '_' + id);
            $j(this).html(theseoptions);
        });
    });
    //then fire it off once to display the correct elements
    $j('#trigger').trigger('change');
});

</script>

【问题讨论】:

  • 从第二个脚本中取出 var $j = jQuery.noConflict(); 并将所有 $j 引用更改为 $
  • 两个脚本都使用 jquery 吗?如果是这样,是的,删除 noConflict 并将 $j 变量更改为 $
  • 你为什么不在一个脚本中做这两个动作?
  • 我尝试在一个脚本中添加两者并获得相同的结果。
  • 所以你有一个&lt;button1&gt;&lt;div1&gt; 元素?

标签: javascript php css


【解决方案1】:

您应该以同样的方式尊重所有文档就绪功能: 通过删除 j 并仅使用 $

第一个 JS 脚本

<script>
$(document).ready(function(){
    $("button1").click(function(){
        $("div1").toggleClass("grid");
    });
});
</script>

第二个 JS 脚本

 <script>
$(document).ready(function () {
    $("#trigger").change(function () {
        if ($(this).data('options') == undefined) {
            $(this).data('options', $('select.switchable option').clone());
        }
        var id = $(this).val();
        var that = this;
        $("select.switchable").each(function () {
            var thisname = $(this).attr('name');
            var theseoptions = $(that).data('options').filter('.' + thisname + '_' + id);
            $(this).html(theseoptions);
        });
    });
    //then fire it off once to display the correct elements
    $('#trigger').trigger('change');
});

</script>

【讨论】:

    猜你喜欢
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多