简体   繁体   English

jQuery简单函数和.html()

[英]Jquery simple function and .html()

As you can see from my code I am pretty new to JQuery and Js. 从我的代码中可以看到,我对JQuery和Js还是很陌生。 So take it easy on me. 所以,请放心我。

Was wondering why this code will not work, I have tried to do the same job many different ways and I just can't seem to make it work.... 我想知道为什么这段代码行不通,我曾尝试以多种不同方式完成相同的工作,而我似乎无法使其正常工作。

    $(function(){

$("<ul id='list'> <li></li> <li></li> <li></li> <li></li> </ul").insertAfter(".content h1");

$("#list li:nth-child(1)").html("<a>",getH2(1),"</a>");
});


function getH2(number) {
    return $(".content h2:nth-of-type(",number,")").text();
}

Here is the full html doc, (only intended for testing, so the code may not be perfect) 这是完整的html文档,(仅用于测试,因此代码可能并不完美)

    <!DOCTYPE html>
<html>
<head>
<title>Specials | The Landon Hotel</title>
<link rel="stylesheet" href="style/style.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="header"><img src="img/header.png"></div>
        <div id="hero">
            <div class="current"><img src="img/HomePageImages/Paris.jpg"></div>
        </div>

<nav class="main-navigation" role="navigation">
<div>
<ul id="menu-main-menu" class="nav-menu">
<li><a href="index.html">Home</a></li>
<li><a href="restaurant-to-room-service.html">Room Service</a></li>
<li><a href="specials.html">Specials</a></li>
<li><a href="reservations.html">Reservations</a></li>
<li><a href="meetings-events.html">Meetings &#038; Events</a></li>
<li><a href="news.html">News</a></li>
<li><a href="contact.html">Contact</a></li>
</ul></div>
</nav>

        <div class="content">   
        <h1>Specials</h1>   
        <h2>San Francisco, Bernal Heights</h2>
        <h3>Military Family Deal:</h3>
        <p>Active and retired military, and their families, save 20% when booking a three or more day stay at the Landon Hotel in lovely Bernal Heights, San Francisco. Book by August 1st, 2015.</p> 
        <h3>Bring Fido:</h3>
        <p>Bring your travel-loving canine to our pet-friendly Bernal Heights Landon Hotel, and see why San Francisco is a dog's paradise, with endless activities and locations that cater to canines. You'll save 10% just for bringing Fido, and there are no hidden pet fees. Book by April 30th, 2014.</p> 
        <h3>Meeting Mondays:</h3>
        <p>The new Bernal Heights conference room is just the place for your corporate meetings, and if you book for three or more consecutive days, that include a Monday, you'll receive Monday free. Book by September 15th, 2014.</p>
<hr/>
        <h2>London, West End</h2>
        <h3>Theatre Package:</h3>
        <p>Theatre lovers can enjoy two free tickets to a West End theater production of their choice, when booking a weekend stay at the West End Landon.  Tickets are mezzanine level and are limited to available productions at the time of booking. Book by August 1st, 2015.</p>
        <h3>Shopper's Paradise:</h3>
        <p>Oxford, Regent, and Bond Streets have some of the best shopping in the world, and all are just a tube stop away when you stay at the West End Landon. And, if you book a minimum of five days, you'll get a bonus gift certificate worth $125 to use in the boutique of your choice, based on participating vendors at time of booking. Book by November 2015.</p>
<hr/>       
        <h2>Hong Kong, Kwun Tong</h2>
        <h3>Spa Holiday:</h3>
        <p>The Hong Kong is home to a half-dozen world-renowned spas, some tucked away in skyscrapers, others in beachside retreats. You can have your pick of a one-day Spa Holiday if you book a five-consecutive night stay during the months of February through April. Book by November 1, 2014.</p>
        <h3>Leisure and Luxury:</h3>
        <p>Stay at the Landon Hotel in the Kwun Tong District and you'll have both leisure and luxury at your fingertips. Play a complimentary round of golf and enjoy a complimentary seaweed body wrap and massage, if you book a weekend stay by August 1st , 2015.</p> 
<hr/>
        <h2>Paris, Latin Quarter</h2>
        <h3>Sweet Deal:</h3>
        <p>Paris is renowned for its delectable pastries and other dessert creations by the most highly skilled chefs in the world. If you book a weekend stay by February 28th, 2015 you'll receive a complimentary dessert tray every night of your stay. Be prepared for a sweet feast!</p>
        <h3>Spiritual Walk:</h3>
        <p>The Latin Quarter is the place to tour some of the world's oldest churches and monasteries. You can enjoy a complimentary church walking tour for two, guided by an entertaining and enlightening guide, if you book a weekend stay by March 1, 2015.</p>
        <h3>Holiday Package:</h3>
        <p id="go">Spend the winter holidays in Paris and enjoy festivity and fine food under a star-filled winter sky. You'll receive 15% off your hotel accommodations, if you reserve for 7 consecutive nights in December 2014 or January 2015.  Book by October 30th, 2014.</p>
<hr/>



    </div>

    <script>

        $(function(){
        $("<ul id='list'> <li></li> <li></li> <li></li> <li></li> </ul>").insertAfter(".content h1");
        $("#list li:nth-child(1)").html("<a>",getH2(1),"</a>");
        });
        function getH2(number) {
            return $(".content h2:nth-of-type("+number+")").text();
        }
    </script>

</body>
</html>

While your original code, once the typos have been addressed, seems to work, giving: 解决了输入错误后,您的原始代码似乎可以工作,并给出:

function getH2(number) {
    return $(".content h2:nth-of-type(" + number + ")").text();
}
$(function () {
    $("<ul id='list'> <li></li> <li></li> <li></li> <li></li> </ul>").insertAfter(".content h1");

    $("#list li:nth-child(1)").html("<a href='#'>" + getH2(1) + "</a>");
});

 function getH2(number) { return $(".content h2:nth-of-type(" + number + ")").text(); } $(function() { $("<ul id='list'> <li></li> <li></li> <li></li> <li></li> </ul>").insertAfter(".content h1"); $("#list li:nth-child(1)").html("<a href='#'>" + getH2(1) + "</a>"); }); 
 #list { color: orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="header"> <img src="img/header.png"> </div> <div id="hero"> <div class="current"> <img src="img/HomePageImages/Paris.jpg"> </div> </div> <nav class="main-navigation" role="navigation"> <div> <ul id="menu-main-menu" class="nav-menu"> <li><a href="index.html">Home</a> </li> <li><a href="restaurant-to-room-service.html">Room Service</a> </li> <li><a href="specials.html">Specials</a> </li> <li><a href="reservations.html">Reservations</a> </li> <li><a href="meetings-events.html">Meetings &#038; Events</a> </li> <li><a href="news.html">News</a> </li> <li><a href="contact.html">Contact</a> </li> </ul> </div> </nav> <div class="content"> <h1>Specials</h1> <h2>San Francisco, Bernal Heights</h2> <h3>Military Family Deal:</h3> <p>Active and retired military, and their families, save 20% when booking a three or more day stay at the Landon Hotel in lovely Bernal Heights, San Francisco. Book by August 1st, 2015.</p> <h3>Bring Fido:</h3> <p>Bring your travel-loving canine to our pet-friendly Bernal Heights Landon Hotel, and see why San Francisco is a dog's paradise, with endless activities and locations that cater to canines. You'll save 10% just for bringing Fido, and there are no hidden pet fees. Book by April 30th, 2014.</p> <h3>Meeting Mondays:</h3> <p>The new Bernal Heights conference room is just the place for your corporate meetings, and if you book for three or more consecutive days, that include a Monday, you'll receive Monday free. Book by September 15th, 2014.</p> <hr/> <h2>London, West End</h2> <h3>Theatre Package:</h3> <p>Theatre lovers can enjoy two free tickets to a West End theater production of their choice, when booking a weekend stay at the West End Landon. Tickets are mezzanine level and are limited to available productions at the time of booking. Book by August 1st, 2015.</p> <h3>Shopper's Paradise:</h3> <p>Oxford, Regent, and Bond Streets have some of the best shopping in the world, and all are just a tube stop away when you stay at the West End Landon. And, if you book a minimum of five days, you'll get a bonus gift certificate worth $125 to use in the boutique of your choice, based on participating vendors at time of booking. Book by November 2015.</p> <hr/> <h2>Hong Kong, Kwun Tong</h2> <h3>Spa Holiday:</h3> <p>The Hong Kong is home to a half-dozen world-renowned spas, some tucked away in skyscrapers, others in beachside retreats. You can have your pick of a one-day Spa Holiday if you book a five-consecutive night stay during the months of February through April. Book by November 1, 2014.</p> <h3>Leisure and Luxury:</h3> <p>Stay at the Landon Hotel in the Kwun Tong District and you'll have both leisure and luxury at your fingertips. Play a complimentary round of golf and enjoy a complimentary seaweed body wrap and massage, if you book a weekend stay by August 1st , 2015.</p> <hr/> <h2>Paris, Latin Quarter</h2> <h3>Sweet Deal:</h3> <p>Paris is renowned for its delectable pastries and other dessert creations by the most highly skilled chefs in the world. If you book a weekend stay by February 28th, 2015 you'll receive a complimentary dessert tray every night of your stay. Be prepared for a sweet feast!</p> <h3>Spiritual Walk:</h3> <p>The Latin Quarter is the place to tour some of the world's oldest churches and monasteries. You can enjoy a complimentary church walking tour for two, guided by an entertaining and enlightening guide, if you book a weekend stay by March 1, 2015.</p> <h3>Holiday Package:</h3> <p id="go">Spend the winter holidays in Paris and enjoy festivity and fine food under a star-filled winter sky. You'll receive 15% off your hotel accommodations, if you reserve for 7 consecutive nights in December 2014 or January 2015. Book by October 30th, 2014.</p> <hr/> 

External JS Fiddle demo for experimentation and development. 用于实验和开发的外部JS Fiddle演示

The problems with your original posted jQuery is the following, that the closing </ul> tag had its closing greater-than omitted (you wrote: </ul ), and string-concatenation in JavaScript is with a plus symbol ( + ) not a comma ( , ): 原始发布的jQuery的问题如下: </ul>标记的结束符大于省略号(您写了: </ul ),JavaScript中的字符串串联不是带有加号( + )的逗号( , ):

$(function () {

    $("<ul id='list'> <li></li> <li></li> <li></li> <li></li> </ul")
    // requires the closing '>' ----------------------------------^
        .insertAfter(".content h1");

    $("#list li:nth-child(1)").html("<a>", getH2(1), "</a>");
    // requires replacement, with a + ---^---------^
});


function getH2(number) {
    return $(".content h2:nth-of-type(", number, ")").text();
    // requires replacement, with a + -^-------^
}

I'd suggest the following instead, for being a little more abstract and functional, in that it creates an 'id' for the elements (though without, in this incarnation, first checking that an 'id' isn't already present), links the created <a> element that links to that 'id' and requires no preexisting knowledge of how many <h2> elements exist (in your original version you were calling getH2() and passing an index to it, which would likely have necessitated calling the function four times and, in each case, having to supply the function call with the appropriate index). 我建议以下内容,因为它具有更多的抽象性和功能性,因为它为元素创建了一个“ id”(尽管在这种情况下,首先不检查是否已存在“ id”),链接创建的<a>元素,该元素链接到该'id' 并且不需要预先存在多少个<h2>元素的知识(在您的原始版本中,您正在调用getH2()并向其传递索引,这可能是必需的调用函数四次,并且在每种情况下都必须为函数调用提供适当的索引)。

That said, here's my suggestion: 也就是说,这是我的建议:

$(function () {

    // creating a <ul> element, using an object to
    // set the named ('id') property of that
    // created element:
    $('<ul />', {
        'id' : 'list'

      // inserting the created-<ul> after the <h1> descendant
      // of the element with the class of 'content':
      }).insertAfter(".content h1")

      // insertAfter returns the original jQuery object,
      // not the element(s) matched by the supplied selector,
      // so here we chain the append() method to supply contents
      // for the created-<ul>:
      .append(function () {

        // here we iterate over the <h2> elements in the document,
        // creating an id for each of the <h2> elements, and then
        // create an Array of HTML creating an <a> element, setting
        // its 'href' to the same 'id' we just created for the <h2>,
        // and settings its text to the same content as the <h2>:
        return '<li>' + $('h2').map(function (i) {
            this.id = 'heading_' + i;
            return '<a href="#heading_' + i + '">' + this.textContent + '</a>';
        // we then join these array elements together with
        // </li><li> to close, then open, <li> elements 
        // (note that the created Array is itself surrounded
        // with an opening '<li>' and a closing '</li>'
        }).get().join('</li><li>') + '</li>'
    });
});

 $(function() { $('<ul />', { 'id': 'list' }).insertAfter(".content h1").append(function() { return '<li>' + $('h2').map(function(i) { this.id = 'heading_' + i; return '<a href="#heading_' + i + '">' + this.textContent + '</a>'; }).get().join('</li><li>') + '</li>' }); }); 
 #list { color: orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="header"> <img src="img/header.png"> </div> <div id="hero"> <div class="current"> <img src="img/HomePageImages/Paris.jpg"> </div> </div> <nav class="main-navigation" role="navigation"> <div> <ul id="menu-main-menu" class="nav-menu"> <li><a href="index.html">Home</a> </li> <li><a href="restaurant-to-room-service.html">Room Service</a> </li> <li><a href="specials.html">Specials</a> </li> <li><a href="reservations.html">Reservations</a> </li> <li><a href="meetings-events.html">Meetings &#038; Events</a> </li> <li><a href="news.html">News</a> </li> <li><a href="contact.html">Contact</a> </li> </ul> </div> </nav> <div class="content"> <h1>Specials</h1> <h2>San Francisco, Bernal Heights</h2> <h3>Military Family Deal:</h3> <p>Active and retired military, and their families, save 20% when booking a three or more day stay at the Landon Hotel in lovely Bernal Heights, San Francisco. Book by August 1st, 2015.</p> <h3>Bring Fido:</h3> <p>Bring your travel-loving canine to our pet-friendly Bernal Heights Landon Hotel, and see why San Francisco is a dog's paradise, with endless activities and locations that cater to canines. You'll save 10% just for bringing Fido, and there are no hidden pet fees. Book by April 30th, 2014.</p> <h3>Meeting Mondays:</h3> <p>The new Bernal Heights conference room is just the place for your corporate meetings, and if you book for three or more consecutive days, that include a Monday, you'll receive Monday free. Book by September 15th, 2014.</p> <hr/> <h2>London, West End</h2> <h3>Theatre Package:</h3> <p>Theatre lovers can enjoy two free tickets to a West End theater production of their choice, when booking a weekend stay at the West End Landon. Tickets are mezzanine level and are limited to available productions at the time of booking. Book by August 1st, 2015.</p> <h3>Shopper's Paradise:</h3> <p>Oxford, Regent, and Bond Streets have some of the best shopping in the world, and all are just a tube stop away when you stay at the West End Landon. And, if you book a minimum of five days, you'll get a bonus gift certificate worth $125 to use in the boutique of your choice, based on participating vendors at time of booking. Book by November 2015.</p> <hr/> <h2>Hong Kong, Kwun Tong</h2> <h3>Spa Holiday:</h3> <p>The Hong Kong is home to a half-dozen world-renowned spas, some tucked away in skyscrapers, others in beachside retreats. You can have your pick of a one-day Spa Holiday if you book a five-consecutive night stay during the months of February through April. Book by November 1, 2014.</p> <h3>Leisure and Luxury:</h3> <p>Stay at the Landon Hotel in the Kwun Tong District and you'll have both leisure and luxury at your fingertips. Play a complimentary round of golf and enjoy a complimentary seaweed body wrap and massage, if you book a weekend stay by August 1st , 2015.</p> <hr/> <h2>Paris, Latin Quarter</h2> <h3>Sweet Deal:</h3> <p>Paris is renowned for its delectable pastries and other dessert creations by the most highly skilled chefs in the world. If you book a weekend stay by February 28th, 2015 you'll receive a complimentary dessert tray every night of your stay. Be prepared for a sweet feast!</p> <h3>Spiritual Walk:</h3> <p>The Latin Quarter is the place to tour some of the world's oldest churches and monasteries. You can enjoy a complimentary church walking tour for two, guided by an entertaining and enlightening guide, if you book a weekend stay by March 1, 2015.</p> <h3>Holiday Package:</h3> <p id="go">Spend the winter holidays in Paris and enjoy festivity and fine food under a star-filled winter sky. You'll receive 15% off your hotel accommodations, if you reserve for 7 consecutive nights in December 2014 or January 2015. Book by October 30th, 2014.</p> <hr/> 

External JS Fiddle demo . 外部JS Fiddle演示

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM