单击按钮时输出特定的JSON

时间:2019-04-13 05:11:29

标签: javascript html json

我使用一些JSON来进行欧几里得相似性实验,这是迈向机器学习的第一步。我有一些使用HTML和CSS创建的按钮,但是我需要一种将JSON的某些部分附加到每个按钮的方法。您可以在similarity函数中看到我对此所做的相当可怜的尝试。如果我不够具体,让我详细介绍一下;例如,对于电影 Dunkirk ,我希望单击该按钮时显示 Dunkirk 的对象。对于脑震荡,我希望显示脑震荡的对象...等等。

<div id="dunk" class="movie">
        <div class="text">Dunkirk</div>
    </div>
    <div id="conc" class="movie">
        <div class="text">Concussion</div>
    </div>
    <div id="indep" class="movie">
        <div class="text">Independence</div>
    </div>
    <div id="freesolo" class="movie">
        <div class="text">Free Solo</div>
    </div>
    <div id="submit">
        <div id="text">Submit</div>
    </div>
.movie {
    height:50px;
    width:80px;
    background-color:grey;
}

.movie:hover {
    background-color:lightgrey;
    cursor:pointer;
}

#submit {
    height:50px;
    width:80px;
    background-color:black;
}

#submit:hover {
    background-color:darkgrey;
    cursor:pointer;
}
let data = 
    [
        [{
            "name": "Dunkirk",
            "action": 7,
            "suspense": 9,
            "drama": 5,
            "character": 2,
            "romance": null,
            "comedy": null,
            "sci-fi": null,
            "interestFactor": 7
        }],
        [{
            "name": "Concussion",
            "action": null,
            "suspense": 7,
            "drama": 8,
            "character": 9,
            "romance": 3,
            "comedy": null,
            "sci-fi": null,
            "interestFactor": 10
            }],
        [{
            "name": "Independence Day: Resurgence",
            "action": 9,
            "suspense": 6,
            "drama": 3,
            "character": 6,
            "romance": 2,
            "comedy": null,
            "sci-fi": 9,
            "interestFactor": 5
            }],
        [{
            "name": "Free Solo",
            "action": 3,
            "suspense": 10,
            "drama": 10,
            "character": 8,
            "romance": null,
            "comedy": null,
            "sci-fi": null,
            "interestFactor": 10
        }]

    ];

let jString = JSON.stringify(data);
let parseData = JSON.parse(jString);
console.log(parseData[0][0]);

let options = document.querySelectorAll(".movie");
let submit = document.getElementById("submit");

submit.addEventListener('click', similarity);

function similarity(){
    options.forEach((el) => {
        el.addEventListener('click', function(ev){
            console.log(parseData[el][el].name);
        });
    });
    console.log("it worked");
};

2 个答案:

答案 0 :(得分:2)

clickdiv之后,您正在将click个侦听器附加到submit。而是附加监听器 divs

let data = [
    {
        "name": "Dunkirk",
        "action": 7,
        "suspense": 9,
        "drama": 5,
        "character": 2,
        "romance": null,
        "comedy": null,
        "sci-fi": null,
        "interestFactor": 7
    },
    {
        "name": "Concussion",
        "action": null,
        "suspense": 7,
        "drama": 8,
        "character": 9,
        "romance": 3,
        "comedy": null,
        "sci-fi": null,
        "interestFactor": 10
        },
    {
        "name": "Independence Day: Resurgence",
        "action": 9,
        "suspense": 6,
        "drama": 3,
        "character": 6,
        "romance": 2,
        "comedy": null,
        "sci-fi": 9,
        "interestFactor": 5
        },
    {
        "name": "Free Solo",
        "action": 3,
        "suspense": 10,
        "drama": 10,
        "character": 8,
        "romance": null,
        "comedy": null,
        "sci-fi": null,
        "interestFactor": 10
    }
];

const movies = document.querySelectorAll('.movie');

movies.forEach((movie) => {
    movie.addEventListener('click', function() {
        const movieName = this.children[0].textContent;
        const found  = data.find(({name}) => name.toLowerCase() === movieName.toLowerCase());
        if(found) {console.log(found);}
    });
});
<div id="dunk" class="movie">
    <div class="text">Dunkirk</div>
</div>
<div id="conc" class="movie">
    <div class="text">Concussion</div>
</div>
<div id="indep" class="movie">
    <div class="text">Independence</div>
</div>
<div id="freesolo" class="movie">
    <div class="text">Free Solo</div>
</div>
<div id="submit">
    <div id="text">Submit</div>
</div>

或者您可以使用includes,因为div中的text与电影名称并不完全相似。示例-Independence Day: Resurgence

let data = [
    {
        "name": "Dunkirk",
        "action": 7,
        "suspense": 9,
        "drama": 5,
        "character": 2,
        "romance": null,
        "comedy": null,
        "sci-fi": null,
        "interestFactor": 7
    },
    {
        "name": "Concussion",
        "action": null,
        "suspense": 7,
        "drama": 8,
        "character": 9,
        "romance": 3,
        "comedy": null,
        "sci-fi": null,
        "interestFactor": 10
        },
    {
        "name": "Independence Day: Resurgence",
        "action": 9,
        "suspense": 6,
        "drama": 3,
        "character": 6,
        "romance": 2,
        "comedy": null,
        "sci-fi": 9,
        "interestFactor": 5
        },
    {
        "name": "Free Solo",
        "action": 3,
        "suspense": 10,
        "drama": 10,
        "character": 8,
        "romance": null,
        "comedy": null,
        "sci-fi": null,
        "interestFactor": 10
    }
];

const movies = document.querySelectorAll('.movie');

movies.forEach((movie) => {
    movie.addEventListener('click', function() {
        const movieName = this.children[0].textContent;
        const found  = data.filter(({name}) => name.toLowerCase().includes(movieName.toLowerCase()));
        if(found.length > 0) {console.log(found[0]);}
    });
});
<div id="dunk" class="movie">
    <div class="text">Dunkirk</div>
</div>
<div id="conc" class="movie">
    <div class="text">Concussion</div>
</div>
<div id="indep" class="movie">
    <div class="text">Independence</div>
</div>
<div id="freesolo" class="movie">
    <div class="text">Free Solo</div>
</div>
<div id="submit">
    <div id="text">Submit</div>
</div>

答案 1 :(得分:1)

我将对此稍有不同,并为您提供一些可用于在对象数组中查找内容的函数(我删除了数组中的数组,制成了一个简单的对象数组)。 lookup返回一个数组(一个),而lookupAll返回数组中的所有匹配项。例如,这将允许您查找“悬念”为6等的地方。 注意,我使用data-name来轻松按名称进行匹配,您可以对任何或所有属性进行匹配。

这几乎也可以在任何浏览器中使用,包括IE6之类的超旧浏览器。

var myApp = myApp || {};
myApp.funcs = {
  indexOf: function(myArray, searchTerm, property) {
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
  },
  indexAllOf: function(myArray, searchTerm, property) {
    var ai = [];
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) ai.push(i);
    }
    return ai;
  },
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  lookupAll: function(myArray, searchTerm, property) {
    return this.lookup(myArray, searchTerm, property, false);
  },
  movieFunc: function(ev) {
    let d = this.dataset.name;
    // console.log(d);
    let found = myApp.funcs.lookup(myApp.data, d, "name", true);
    results.textContent = found != undefined ? JSON.stringify(found[0]) : "Not Found";
  }
};
myApp.data = [{
    "name": "Dunkirk",
    "action": 7,
    "suspense": 9,
    "drama": 5,
    "character": 2,
    "romance": null,
    "comedy": null,
    "sci-fi": null,
    "interestFactor": 7
  },
  {
    "name": "Concussion",
    "action": null,
    "suspense": 7,
    "drama": 8,
    "character": 9,
    "romance": 3,
    "comedy": null,
    "sci-fi": null,
    "interestFactor": 10
  },
  {
    "name": "Independence Day: Resurgence",
    "action": 9,
    "suspense": 6,
    "drama": 3,
    "character": 6,
    "romance": 2,
    "comedy": null,
    "sci-fi": 9,
    "interestFactor": 5
  },
  {
    "name": "Free Solo",
    "action": 3,
    "suspense": 10,
    "drama": 10,
    "character": 8,
    "romance": null,
    "comedy": null,
    "sci-fi": null,
    "interestFactor": 10
  }
];


let movies = document.querySelectorAll(".movie");
let submit = document.getElementById("submit");
let results = document.getElementById("results");
submit.addEventListener('click', similarity);

function movieFunc(ev) {
  let d = this.dataset.name;
  // console.log(d);
  let found = myApp.funcs.lookup(myApp.data, d, "name", true);
  results.textContent = found != undefined ? JSON.stringify(found[0]) : "Not Found";
}
movies.forEach((el) => {
  el.addEventListener('click', myApp.funcs.movieFunc);
});

function similarity() {
  console.log("it worked");
};
.movie {
  height: 2em;
  width: 20em;
  border: solid 1px blue;
}

.movie:hover {
  background-color: lightgrey;
  cursor: pointer;
}

#results {
  border: solid lime 1px;
}

#submit {
  height: 2em;
  width: 20em;
  background-color: #bbbbbb;
}

#submit:hover {
  border: solid 1px blue;
  cursor: pointer;
}
<div id="dunk" class="movie" data-name="Dunkirk">
  <div class="text">Dunkirk</div>
</div>
<div id="conc" class="movie" data-name="Concussion">
  <div class="text">Concussion</div>
</div>
<div id="indep" class="movie" data-name="Independence Day: Resurgence">
  <div class="text">Independence</div>
</div>
<div id="freesolo" class="movie" data-name="Free Solo">
  <div class="text">Free Solo</div>
</div>
<div id="submit">
  <div id="text">Submit</div>
</div>
<div id="results">&nbsp</div>