【问题标题】:Get Javascript to work? $.ajax not working right?让 Javascript 工作? $.ajax 不能正常工作?
【发布时间】:2013-07-01 15:20:23
【问题描述】:

因此,可以在下面找到的 Javascript 代码似乎无法正常运行。

目标是让地图下方的文本在房间悬停时发生变化。

Map Page

我认为,提取数据的 JSON (zadias.me/SVG/rooms.json) 数据似乎是我的错误所在。当我通过放置将在文本字段中打印的 .innerHTML 语句来测试/调试代码时,如果我将 .innerHTML 放在 $.ajax 之前,它将起作用,但是,如果我将 .innerHTML 函数放在“成功”部分的.ajax,它不起作用..

Javascript:

$(document).ready(function(){
var json = (function () { //this function obtains the data
    var json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': 'http://zadias.me/SVG/rooms.json',
        'dataType': "json",
        'success': function (data) { 
            json = data;
        }
    });
    return json;
})();

function hashTag(){
    var hashTag, hash2;

    hashTag = location.hash; //obtains the part of the URL with the hash tag and what follows
    hashTag = hashTag.replace(/#*/, ''); //replaces the hash tag

    if(hashTag.length > 0){
        for(i=0 ; i<json.rooms.length ; i++){
            if (json.rooms[i].roomId == hashTag) //linear search through array of rooms to see if any equal the hashTag
            {
            document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
            } //loads the data from the JSON data.
        }
    }
}; 

function setHash(){
    window.location.hash = this.id; //creates the hash link based on the object's id (object id acquired from the JSON data) and sets it
};

function setHTML(){
    for(i=0 ; i<json.rooms.length ; i++){
    if (json.rooms[i].roomId == this.id)
    {
    document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
    }
  }
};

window.onload = hashTag();
$(".active").click(setHash);
$(".active").mouseenter(setHTML);
//$(".active").mouseover(setHTML);
$(".active").mouseleave(hashTag);
});

我知道它有点本地化,我该如何更改?

【问题讨论】:

  • 你能把你的相关代码贴在这里吗?
  • 'async': false, 是一个非常糟糕的主意。在 ajax 调用期间锁定浏览器。
  • Uncaught TypeError: Cannot read property 'style' of nullPresParkEisenhower2.svg 的第 1 行。 document.body.style 导致它。
  • 谢谢@Archer!我摆脱了它,我似乎没有看到任何改善..@jfriend00 我尝试摆脱'async':false,但它似乎没有多大作用。

标签: javascript jquery svg hover


【解决方案1】:

如果我做对了,您需要将变量 json 设为全局变量。把开头的var 去掉,看看有没有帮助。

【讨论】:

  • 值得一试。我唯一能建议的是放入一些console.log() 语句来转储变量值并检查它们,或者使用调试器并逐步执行代码。
  • 我现在已经完成了。鼠标悬停只返回 id 为 svg 的元素。看起来您无法按照您的方式选择房间。 (转到控制台并输入$(".active"))。
  • 我对 Javascript 比较陌生,对 console.log() 不太熟悉。我会对此进行一些研究,希望它会有所帮助。感谢您的帮助!
  • 从进一步阅读看来,以您尝试的方式解析 svg 元素似乎很困难。我会先在谷歌上搜索一下。
【解决方案2】:

您可能想尝试更多类似的方法:

// this returns a promise
var json,
    response = $.ajax({
        'async': false,
        'global': false,
        'url': 'http://zadias.me/SVG/rooms.json',
        'dataType': "json",
        'success': function (data) { 
            json = data;
        }
    });

window.onload = function() {
    // ensures that the ajax has returned a value
    response.done(hashTag);
};

文档实际上并不一定要为您运行 AJAX 请求做好准备。

您可能需要查看此处以访问 SVG 元素:How to access SVG elements with Javascript。需要从 更改为

【讨论】:

    【解决方案3】:

    这是您的代码版本,其中包含一些更新:

    var json;
    
    $(document).ready(function(){
        $.ajax({
            'global': false,
            'url': 'http://zadias.me/SVG/rooms.json',
            'dataType': "json",
            'success': function (data) {
                json = data;
                hashTag();
                $(".active")
                    .click(setHash)
                    .mouseenter(setHTML)
                    .mouseleave(hashTag);
            }
        });
    });
    
    function hashTag(){
        //get everything in the URL after the #
        var hash = location.hash.replace(/#*/, '');
    
        if(hash.length > 0){
            //linear search through array of rooms to find the hashTag
            $.each( json.rooms, function( room ) {
                if (room.roomId == hash) {
                    $('#room_info').html(
                        '<img src="images/' + room.image + '" /><h4>' +
                        room.name + '</h4>' + room.HTMLdescrip
                    );
                } //loads the data from the JSON data.
            });
        }
    };
    
     // creates the hash link based on the object's id
     // (object id acquired from the JSON data) and sets it
    function setHash(){
        window.location.hash = this.id;
    }
    
    function setHTML(){
        $.each( json.rooms, function( room ) {
            if (room.roomId == this.id) {
                $('#room_info').html(
                    '<img src="images/' + room.image + '" /><h4>' +
                    room.name + '</h4>' + room.HTMLdescrip
                );
            }
        });
    }
    

    我改变了什么:

    1. json 变量设为全局变量。
    2. 删除了async:true。永远不要使用它!
    3. 删除了global:false。您没有任何全局 Ajax 事件处理程序,因此此标志无效。
    4. 删除了 $.ajax() 属性名称周围不必要的引号。
    5. 删除了代码末尾的事件处理程序设置。
    6. 将初始化移到$.ajax() 回调中,因为那是数据准备就绪的时候。
    7. $(".active") 上的事件处理程序设置链接在一起,而不是重复选择器调用。
    8. 为简单起见,使用 $.each() 而不是 for 循环。
    9. 感谢$.each(),将json.rooms[i] 引用更改为room
    10. 使用$('#foo').html(html) instead ofdocument.getElementById()and.innerHTML`,再次为简单起见。
    11. 简化了 hashTag 变量的设置并将其名称更改为 hash 以避免与函数名称混淆。
    12. 删除了函数定义末尾不必要的分号。
    13. 使缩进和格式更加一致。
    14. 缩短了多余的行长。

    其中一些更改只是风格上的,但我推荐它们。看完代码自然就可以从中挑选了。

    重要的一点是确保json 数据不仅在需要的地方可用,而且在需要时 可用,并且不使用async:false

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 2022-12-04
      • 2014-02-25
      • 2021-11-16
      相关资源
      最近更新 更多