简体   繁体   English

Javascript与WordPress冲突

[英]Javascript conflict with WordPress

I got this geolocation working but if I put it in WordPress it stops working. 我可以使用此地理位置,但是如果将其放在WordPress中,它将停止工作。 What's wrong with this? 这怎么了

http://jsfiddle.net/spzg5oL8/3/ http://jsfiddle.net/spzg5oL8/3/

$.get("http://freegeoip.net/json/", function (response) {
    $("#ip").html("IP: " + response.ip);
    //$("#country_code").html(response.country_code);
    document.getElementsByClassName(response.country_code)[0].style.display = "block";
}, "jsonp");

This will not work in WordPress for one reason (for sure), and another reason (potentially): 由于某种原因(肯定)和另一种原因(潜在地),这在WordPress中将不起作用:

First, you cannot use the $ for jQuery in WordPress. 首先,您不能在WordPress中将$用于jQuery。 WordPress loads jQuery in "no-conflict" mode, which means you have to use jQuery , OR wrap this in a document ready method to "inject" the $ : WordPress以“无冲突”模式加载jQuery,这意味着您必须使用jQuery ,或将其包装在文档就绪方法中以“注入” $

 jQuery(function($) {
    $.get("http://freegeoip.net/json/", function (response) {
        $("#ip").html("IP: " + response.ip);
        //$("#country_code").html(response.country_code);
        // Why don't you use jQuery here, for simplicity?
        // $('.' + response.country_code).style('display', 'block');
        document.getElementsByClassName(response.country_code)[0].style.display = "block";
    }, "jsonp");
});

Second, you have to be sure that jQuery is loaded on your WordPress site. 其次,您必须确保jQuery网站上已加载 jQuery。 Whatever you do, do not just hard-code a link to jQuery in the header of the site, but rather, in the functions.php file for the theme (or plugin) add the below php: 无论您做什么, 不仅要在网站标题中硬编码指向jQuery的链接,还要在主题(或插件)的functions.php文件中添加以下php:

add_action('wp_enqueue_scripts', 'load_my_scripts');

function load_my_scripts() {
    wp_enqueue_script('jquery');
}

Adding to what @cale_b said, you can see the call to jQuery.noConflict(); 除了@cale_b所说的之外,您还可以看到对jQuery.noConflict();的调用jQuery.noConflict(); as the last line of Wordpress's jQuery file: 作为Wordpress的jQuery文件的最后一行:

/wp-includes/js/jquery/jquery.js

I haven't found anything explicitly in the documentation, but seeing it in the code helps to know what's happening. 我没有在文档中明确找到任何内容,但是在代码中看到它有助于了解发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM