在相同的html上使用相同的脚本和不同的输入

时间:2016-03-26 21:12:20

标签: javascript jquery html

我试图让JavaScript在html代码的不同部分使用相同的代码,脚本从特定的url请求中读取标题,运行时和绘图,并将该信息放在正确的div中。我怎么能这样做?

http://www.omdbapi.com/?i=tt0110912&plot=short&r=json  (Pulp Fiction Movie)
http://www.omdbapi.com/?i=tt0796366&plot=short&r=json  (Star Trek Movie)
http://www.omdbapi.com/?i=tt0251413&plot=short&r=json  (Star Wars Movie)

为每部电影调用以下网址:

var search = document.getElementById('dividhere').value;
xhr.open('GET', 'http://www.omdbapi.com/?i=+search+&plot=short&r=json', true);
xhr.send();
}

如何使用正确的?i = tt *******信息向div添加id,以便脚本为标题,运行时和绘图部分添加正确的答案?

想一想脚本应该读取div id,使用该id来获取信息:

var cond = '{ location :'+ value +'}'; places.findOne(cond, function ...

脚本应该读取并运行带有该id信息的xhr.open,将获取的信息放在该div中并在第二个div上运行脚本,然后再在第三个div上运行。因此,如果我添加另一个带有新id信息的div,脚本将加载新电影。

2 个答案:

答案 0 :(得分:0)

好的,使用JQuery(请使用它)。首先,将类添加到div:

<div class="movie" id="tt0796366"> <!-- Star Trek -->

然后:

$('.movie').each(function(i, item) {
    $.getJSON('http://www.omdbapi.com/?i='+ $(this).attr('id') +'&plot=short&r=json', function(data) {
       $(item).find('h1').html(data.title);
       ....
   });
});

答案 1 :(得分:0)

您可以使用JS动态呈现HTML,如下所示(https://jsfiddle.net/6usmu7ny/1/):

的JavaScript

var items = document.querySelectorAll('[name="img-descr"]');
var loaded = [];

for(var i = 0; i < items.length; i++) {
    items[i].addEventListener('click', function(evt) {
        renderMovie(evt.target.nextElementSibling)
      }, false);
}

function renderMovie(el) {
    var movie = el.id

    if(loaded.indexOf(movie) !== -1) return;

    loaded.push(movie);

    getMovieInformation(movie, function(data) {
        var title = document.createTextNode(data.Title);
        var runtime = document.createTextNode(data.Runtime);
        var plot = document.createTextNode(data.Plot);

        el.querySelector('#Title').appendChild(title);
        el.querySelector('#Runtime').appendChild(runtime);
        el.querySelector('#Plot').appendChild(plot);
    }); 
};

function getMovieInformation(movie, cb) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var fullMovie = JSON.parse(xhr.responseText);
            cb(fullMovie);
        }
    }
    xhr.open("GET", 'https://www.omdbapi.com/?i='+movie+'&plot=short&r=json');
    xhr.send();
}