我有一个 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/