【问题标题】:Using $ instead of jQuery in wordpress child theme在 wordpress 子主题中使用 $ 而不是 jQuery
【发布时间】:2013-10-31 12:58:27
【问题描述】:

$我正在使用二十三主题的子主题构建一个 wordpress (v. 3.6) 站点。 我的主题的 header.php 有

<body <?php body_class(); ?> onResize="resizeHandler();">

这是主题的 .js 文件,myChildTheme.js:

var myStuff;
function resizeHandler() {
    myStuff = jQuery(".stuff");
    console.log("resized, and here's stuff: "+ myStuff);
}

为了使用 $ 而不是“jQuery”,我尝试了在网上找到的解决方案。新的 myChildTheme.js:

jQuery(document).ready(function($) {
    var myStuff;
    function resizeHandler() {
        myStuff = $(".stuff");
        console.log("resized, and here's stuff: "+ myStuff);
    }
});

然后我得到一个控制台引用错误,说 resizeHandler 没有定义。

我已经以我认为正确的方式排队并注册了主题的脚本和样式。

functions.php:

function myChildTheme_scripts_styles() {
    wp_enqueue_style( 'myChildTheme-fonts', myChildTheme_fonts_url(), array(), null );
}
add_action( 'wp_enqueue_scripts', 'myChildTheme_scripts_styles' );

function myChildTheme_scripts() {
    wp_enqueue_script('myChildTheme_functions', get_stylesheet_directory_uri().'/js/myChildTheme.js', array('jquery'), '', true);
    wp_enqueue_script('isotope_source', get_stylesheet_directory_uri().'/js/jquery.isotope.min.js', array('jquery'), '', true);
}
add_action( 'wp_enqueue_scripts', 'myChildTheme_scripts' );

关于如何让 $ 工作的任何提示?谢谢。

【问题讨论】:

  • .ready(function($) { 内你可以使用$ 代替jQuery
  • 通过将代码包装在 document.ready 处理程序中,您正在降低它的可见性。处理程序之外的任何东西都看不到它。另外,我没有看到您尝试在任何地方使用$
  • 对不起,我忘了使用正确的例子和$。我现在更正了。

标签: jquery wordpress themes


【解决方案1】:

您需要通过 jQuery 本身附加 resize 事件。试试这个:

<body <?php body_class(); ?>>
jQuery(document).ready(function($) {
    var myStuff;
    function resizeHandler() {
        myStuff = $(".stuff"); // note $ use here
        console.log("resized, and here's stuff: "+ myStuff);
    }

    $(window).resize(resizeHandler);
});

仅供参考,您的控制台将输出 resized, and here's stuff: [Object object] - 这是正常的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多