onclick函数动态填充新页面无效

时间:2016-03-10 10:46:14

标签: jquery handlebars.js

我是编程新手,而且只是在我的第二个月的在线课程中。我不熟悉编写术语以有效地谷歌寻求帮助或在Stackoverflow上搜索此特定问题。然而,我已经克服了onclick函数引用其他stackoverflow答案的初始问题。

我使用过把手并有2个模板。 2个html文件index.html和details.html,1个数据文件和1个js文件(2个单独的文件)。

索引基本上是由模板生成的菜单,该模板从数据文件中的数组中提取列表。我接下来想要实现的功能是单击一个菜单项,然后打开details.html并根据我点击的菜单项填充details.html模板。

                <!-- start template -->
        <script id="category_template" type="text/x-handlebars-template">

        <div class="row-fluid">
        <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
        <br />
        <div class="list-group">
            <a class="list-group-item active">
            Click a species below to read more
            </a>
        {{#each category}}
            <a href="#" id="detailsbtn" data-id="{{@index}}" class="list-group-item">{{name}}</a>
        {{/each}}
        </div>

        </div>

        </div>

        </script>

    <script id="details_template" type="text/x-handlebars-template">

        <div class="row-fluid">
            {{#each animals}}
            <div style="display: inline-block;" class="col-xs-12 col-sm-6 col-md-6 col-lg-4">                   
            <h3>{{name}}</h3>
            <img src="{{image1}}" alt="{{name}}" class="img-responsive img-circle"><br/>
            <p style="height: 740px">{{description}}</p> 
            </div>
            {{/each}}
        </div>

    </script>
    <!-- / template -->

我现在已将a标签的href设置为#,因为如果我将其设置为details.html,则无论我点击什么项目,它都会显示数组位置0的项目信息。通过将其设置为#我也可以在控制台中看到结果。根据控制台,onclick正在工作,var speciesNum正在更新。但它并没有将该变量保留在details.html的负载上。

问题:虽然我的onclick工作正常,但我的详细信息页面并未反映出onclick更改。

任何帮助将不胜感激。感谢。

$(document).ready(function(){

// get the HTML for the template
// and compile it
var source   = $("#category_template").html();
var template = Handlebars.compile(source);

source   = $("#details_template").html();
var details_template = Handlebars.compile(source);

// Set variable speciesNum for use in rendering template
var speciesNum = 0;

//render the data into the template
var html = template(animalsdata);
var details_html = details_template(animalsdata.category[speciesNum]);

//put the rendered data into DOM
$("#content").html(html);
$("#contentdetail").html(details_html);

//onclick function for home page species menu

$('.list-group-item').on('click', function () {
    var speciesNum = $(this).data("id");
    var details_html = details_template(animalsdata.category[speciesNum]);
    $("#contentdetail").html(details_html);
    console.log(speciesNum);
    console.log(details_html)
});
});

这是数据数组

var animalsdata = {
    category : [
        {
            name : "Reptiles",
            animals : [
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Coast_Garter_Snake.jpg/500px-Coast_Garter_Snake.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Nerodia_sipedon_shedding.JPG/440px-Nerodia_sipedon_shedding.JPG",
                    name : "Snake",
                    description : "Snakes are elongated, legless, carnivorous reptiles of the suborder Serpentes that can be distinguished from legless lizards by their lack of eyelids and external ears. Like all squamates, snakes are ectothermic, amniote vertebrates covered in overlapping scales. Many species of snakes have skulls with several more joints than their lizard ancestors, enabling them to swallow prey much larger than their heads with their highly mobile jaws. To accommodate their narrow bodies, snakes' paired organs (such as kidneys) appear one in front of the other instead of side by side, and most have only one functional lung. Some species retain a pelvic girdle with a pair of vestigial claws on either side of the cloaca. Living snakes are found on every continent except Antarctica, and on most smaller land masses — exceptions include some large islands, such as Ireland and New Zealand, and many small islands of the Atlantic and central Pacific.[3] Additionally, sea snakes are widespread throughout the Indian and Pacific Oceans. More than 20 families are currently recognized, comprising about 500 genera and about 3,400 species.[4][5] They range in size from the tiny, 10 cm-long thread snake to the reticulated python of up to 6.95 meters (22.8 ft) in length.[6] The fossil species Titanoboa cerrejonensis was 13 meters (43 ft) long.[7] Snakes are thought to have evolved from either burrowing or aquatic lizards, perhaps during the Jurassic period, with the earliest known fossils dating to between 143 and 167 Ma ago.[8] The diversity of modern snakes appeared during the Paleocene period (c 66 to 56 Ma ago). The oldest preserved descriptions of snakes can be found in the Brooklyn Papyrus. Most species are nonvenomous and those that have venom use it primarily to kill and subdue prey rather than for self-defense. Some possess venom potent enough to cause painful injury or death to humans. Nonvenomous snakes either swallow prey alive or kill by constriction."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Crocodilia_collage.jpg/600px-Crocodilia_collage.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Caiman_crocodilus_Tropicario_2.JPG/440px-Caiman_crocodilus_Tropicario_2.JPG",
                    name : "Crocodilia",
                    description : "The Crocodilia (or Crocodylia) are an order of large, predatory, semiaquatic reptiles. They appeared 83.5 million years ago in the Late Cretaceous period (Campanian stage) and are the closest living relatives of birds, as the two groups are the only known survivors of the Archosauria. Members of the crocodilian total group, the clade Pseudosuchia, appeared about 250 million years ago in the Early Triassic period, and diversified during the Mesozoic era. The order Crocodilia includes the true crocodiles (family Crocodylidae), the alligators and caimans (family Alligatoridae), and the gharial and false gharial (family Gavialidae). Although the term 'crocodiles' is sometimes used to refer to all of these, a less ambiguous vernacular term for this group is crocodilians."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Bartagame_fcm.jpg/500px-Bartagame_fcm.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Lizard_in_Yemen.JPG/440px-Lizard_in_Yemen.JPG",
                    name : "Lizard",
                    description : "Lizards are a widespread group of squamate reptiles, with approximately over 6,000 species,[1] ranging across all continents except Antarctica, as well as most oceanic island chains. The group, traditionally recognized as the suborder Lacertilia, is defined as all extant members of the Lepidosauria (reptiles with overlapping scales) that are neither sphenodonts (i.e., tuatara) nor snakes – they form an evolutionary grade.[2] While the snakes are recognized as falling phylogenetically within the Toxicofera clade from which they evolved, the sphenodonts are the sister group to the squamates, the larger monophyletic group, which includes both the lizards and the snakes."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Chelonia_mydas_is_going_for_the_air.jpg/440px-Chelonia_mydas_is_going_for_the_air.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1d/Turtle3m.JPG/500px-Turtle3m.JPG",
                    name : "Turtle",
                    description : "Turtles are reptiles of the order Testudines (or Chelonii[3]) characterised by a special bony or cartilaginous shell developed from their ribs and acting as a shield.[4] \"Turtle\" may refer to the order as a whole (American English) or to fresh-water and sea-dwelling testudines (British English). The order Testudines includes both extant (living) and extinct species. The earliest known members of this group date from 157 million years ago,[1] making turtles one of the oldest reptile groups and a more ancient group than snakes or crocodilians. Of the 327 known species alive today, some are highly endangered."
                },
            ]
        },
        {
            name : "Mammals",
            animals : [
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/AfricanWildCat.jpg/440px-AfricanWildCat.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Kittyply_edit1.jpg/440px-Kittyply_edit1.jpg",
                    name : "Cat",
                    description : "The domestic cat (Felis catus or Felis silvestris catus) is a small, usually furry, domesticated, and carnivorous mammal. They are often called housecats when kept as an indoor pet or simply cats when there is no need to distinguish them from other felids and felines.[6] Cats are often valued by humans for companionship and their ability to hunt vermin."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Poligraf_Poligrafovich.JPG/340px-Poligraf_Poligrafovich.JPG",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Cavalier_King_Charles_Spaniel_trio.jpg/440px-Cavalier_King_Charles_Spaniel_trio.jpg",
                    name : "Dog",
                    description : "The domestic dog (Canis lupus familiaris or Canis familiaris) is a domesticated canid which has been selectively bred for millennia for various behaviors, sensory capabilities, and physical attributes. Although initially thought to have originated as a manmade variant of an extant canid species (variously supposed as being the dhole, golden jackal, or gray wolf), extensive genetic studies undertaken during the 2010s indicate that dogs diverged from other wolf-like canids in Eurasia 40,000 years ago. Being the oldest domesticated animals, their long association with people has allowed dogs to be uniquely attuned to human behavior, as well as thrive on a starch-rich diet which would be inadequate for other canid species."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Diademed_ready_to_push_off.jpg/440px-Diademed_ready_to_push_off.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Three_chimpanzees_with_apple.jpg/640px-Three_chimpanzees_with_apple.jpg",
                    name : "Primate",
                    description : "A primate is a mammal of the order Primates (Listeni/praɪˈmeɪtiːz/ pry-may-teez; Latin: \"prime, first rank\"). In taxonomy, primates include two distinct lineages, strepsirrhines and haplorhines. Primates arose from ancestors that lived in the trees of tropical forests; many primate characteristics represent adaptations to life in this challenging three-dimensional environment. Most primate species remain at least partly arboreal. With the exception of humans, who inhabit every continent, most primates live in tropical or subtropical regions of the Americas, Africa and Asia.[4] They range in size from Madame Berthe's mouse lemur, which weighs only 30 g (1 oz), to the eastern lowland gorilla, weighing over 200 kg (440 lb). Based on fossil evidence, the earliest known true primates, represented by the genus Teilhardina, date to 55.8 million years old.[5] An early close primate relative known from abundant remains is the Late Paleocene Plesiadapis, circa 55–58 million years old.[6] Molecular clock studies suggest that the primate branch may be even older, originating near the Cretaceous–Paleogene boundary or around 63-74 mya"
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/%D0%9C%D1%8B%D1%88%D1%8C_2.jpg/500px-%D0%9C%D1%8B%D1%88%D1%8C_2.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Fancy_mice.jpg/500px-Fancy_mice.jpg",
                    name : "Mouse",
                    description : "A mouse (plural: mice) is a small rodent characteristically having a pointed snout, small rounded ears, a body-length scaly tail and a high breeding rate. The best known mouse species is the common house mouse (Mus musculus). It is also a popular pet. In some places, certain kinds of field mice are locally common. They are known to invade homes for food and shelter."
                },
            ]
        },
        {
            name : "Birds",
            animals : [
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/American_Flamingo_-_Phoenicopterus_ruber.jpg/440px-American_Flamingo_-_Phoenicopterus_ruber.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Caribbean_flamingo.jpg/440px-Caribbean_flamingo.jpg",
                    name : "American flamingo",
                    description : "The American flamingo (Phoenicopterus ruber) is a large species of flamingo closely related to the greater flamingo and Chilean flamingo. It was formerly considered conspecific with the greater flamingo, but that treatment is now widely viewed (e.g. by the American and British Ornithologists' Unions) as incorrect due to a lack of evidence. It has also been known as the Caribbean flamingo, but the species' presence in the Galápagos makes that name problematic. It is the only flamingo which naturally inhabits North America"
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Papageitaucher_Fratercula_arctica.jpg/600px-Papageitaucher_Fratercula_arctica.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Atlantic_Puffin_Fratercula_arctica.jpg/440px-Atlantic_Puffin_Fratercula_arctica.jpg",
                    name : "Atlantic puffin",
                    description : "The Atlantic puffin (Fratercula arctica), also known as the common puffin, is a species of seabird in the auk family. It is the only puffin native to the Atlantic Ocean; two related species, the tufted puffin and the horned puffin, are found in the northeastern Pacific. The Atlantic puffin breeds in Iceland, Norway, Greenland, Newfoundland and many North Atlantic islands, and as far south as Maine in the west and the British Isles in the east. The Atlantic puffin has a large population and a wide range. It is not considered to be endangered although there may be local declines in numbers. On land, it has the typical upright stance of an auk. At sea, they swim on the surface and feed mainly on small fish, which they catch by diving underwater, using their wings for propulsion."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/%C3%81guila_calva.jpg/440px-%C3%81guila_calva.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Golden_Eagle_in_flight_-_5.jpg/440px-Golden_Eagle_in_flight_-_5.jpg",
                    name : "Eagle",
                    description : "Eagle is a common name for many large birds of prey of the family Accipitridae; it belongs to several groups of genera that are not necessarily closely related to each other. Most of the 60 species of eagles are from Eurasia and Africa.[1] Outside this area, just 14 species can be found – two in North America, nine in Central and South America, and three in Australia."
                },
                {
                    image1 : "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Ara_ararauna_Luc_Viatour.jpg/440px-Ara_ararauna_Luc_Viatour.jpg",
                    image2 : "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Rose-ringed_Parakeet_eating_leaves.JPG/440px-Rose-ringed_Parakeet_eating_leaves.JPG",
                    name : "Parrot",
                    description : "Parrots, also known as psittacines /ˈsɪtəsaɪnz/,[2][3] are birds of the roughly 372 species in 86 genera that make up the order Psittaciformes, found in most tropical and subtropical regions. The order is subdivided into three superfamilies: the Psittacoidea (\"true\" parrots), the Cacatuoidea (cockatoos) and the Strigopoidea (New Zealand parrots).[5] Parrots have a generally pantropical distribution with several species inhabiting temperate regions in the Southern Hemisphere as well. The greatest diversity of parrots is in South America and Australasia."
                },
            ]
        },

    ]
};

0 个答案:

没有答案