javascript - 在 javascript 对象中查找属性

标签 javascript jquery json jsonp

我有一个 javascript 对象,它是从 JSONP 文件中接收到的。

该对象包含多个“选项”和“结果”,用于在用户点击时调整页面上的html。

现在,我可以检查 HTML 字符串(通过 json 引用插入)是否存在于 json 文件中。我想要做的是获取该字符串,在 json 文件中找到下一个“结果”或“选项”,然后返回该“选项”或“结果”值,以便我可以使用它来更改 html...

我该怎么做?我一直在尝试使用 .indexOf 方法来查找当前索引,但这并不能真正帮助我找到像“选项”这样的特定属性。

这是我用来遍历 JSONP 文件并查找当前字符串是否存在的代码。

$.ajax({
    url: "http://www.myurl.com/jsonp.php",
    type: "GET",
    dataType: "jsonp",
    jsonpCallback: "otmjsonp",
    async: false,
    success: function (JSON) {
        $(".result").on("click", function () {
            var currentResult = $(this).text(); //.result is the line of HTML the user has clicked
            for (var playerSelection in JSON) {
                if (JSON.hasOwnProperty(playerSelection)) {
                    if (JSON[playerSelection] === currentResult) {
                        alert("this selection exists in the JSON");
                    }
                }
            }
        })
    }
});

这是大型 JSONP 文件的一个非常简单的版本:

otmjsonp({
"situation1" : "Your opponent is trying to tackle you", "playerPrompt1" : "What will you do first?", 

"option1" : "avoid him",

    "result1" : "he tackles you",

        "situation2" : "you were tackled", "playerPrompt2" : "Your opponent begins to slow down",

        "option2" : "chase after him",
            "result2" : "you caught up",
)}

等等等

即使是模糊的想法/方向也会受到赞赏,因为我完全被困住了。

最佳答案

这里的部分问题在于您如何将 UI 与数据初始化相结合。我认为您真正想要做的是将获取数据的 JSON 请求与点击处理分开。

$(function() {

  var setupHTML, 
      handleClick,
      updateHTML,
      originalData,
      resultData;

  updateHTML = function(JSON) {
    // Add or activate the html the person is clicking
    $('.result').text()
  };

  handleClick = function(e) {
    var currChoice = $(e.target).text();

    if (resultData === undefined) {
      e.stopPropagation();
      e.preventDefault();
      return;
    }

    for (var ps in resultData) {
      if (resultData.hasOwnProperty(ps) && resultData[ps] === currChoice) {
        resultData = resultData[ps];
        updateHTML(resultData);
      }
    }
  }

  $('.result').on('click', handleClick)


  $.ajax({
    url: "http://www.myurl.com/jsonp.php",
    type: "GET",
    dataType: "jsonp",
    jsonpCallback: "otmjsonp",
    async: false,
    success: function(data) {
      resultData = origData = data;

      // make the UI visible
      setupHTML(JSON);
    }
    });

});

关于javascript - 在 javascript 对象中查找属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17255945/

相关文章:

json - Grails - grails.converters.JSON - 删除类名

Javascript从对象数组中删除重复值

javascript - Knockout.js ReferenceError - 无法解析绑定(bind) $data 未定义

javascript - HTML转图片时如何显示图片

php - AJAX-PHP 组合 : $. 将复选框值发送到 PHP

JQuery 获取具有特定类的所有元素并删除 CSS 属性

java - Gson 解析响应以获取泛型类

json - 通过将项目添加到其包含数字数组的分支之一来更新 JsObject

javascript - 如何一次运行一次循环javascript

javascript - 将局部变量传递给回调函数