zoukankan      html  css  js  c++  java
  • Javascript DOM 编程艺术:创建一个简单的gallery

    开始的html如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta http-equiv="content-type" content="text/html; charset=utf-8" />
      <title>Image Gallery</title>
    </head>
    <body>
      <h1>Snapshots</h1>
      <ul>
        <li>
          <a href="images/fireworks.jpg" title="A fireworks display">Fireworks</a>
        </li>
        <li>
          <a href="images/coffee.jpg" title="A cup of black coffee">Coffee</a>
        </li>
        <li>
          <a href="images/rose.jpg" title="A red, red rose">Rose</a>
        </li>
        <li>
          <a href="images/bigben.jpg" title="The famous clock">Big Ben</a>
        </li>
      </ul>
    <img id="placeholder" src="images/placeholder.gif" alt="placeholder" />
    <p id="description">Choose an image.</p>
    
    </body>
    </html>

    This is a perfectly fine web page, but the default behavior isn’t ideal. These are the things
    I want to happen instead:
    When I click a link, I want to remain on the same page.
    When I click a link, I want to see the image on the same page that has my original
    list of images.

    This is how I’m going to do it:
    I’ll put a placeholder image on the same page as the list.
    When I click a link, I’ll intercept the default behavior.
    I’ll replace the placeholder image with the image from the link.

    刚开始的js如下:

    function showPic(whichpic) {
      var source = whichpic.getAttribute("href");
      var placeholder = document.getElementById("placeholder");
      placeholder.setAttribute("src",source);
    }

    在<a> 增加

      onclick = "showPic(this);"

    会发现我们还是跳转到了图像,(其实showPic已经调用了,只不过两种同时触发)。

    However, if I simply add this event handler to a link in my list, I’m going to be faced with a
    problem. The function will be invoked, but the default behavior for clicking on a link will
    also be invoked. This means that the user will be taken to the image—exactly what I didn’t
    want to happen. I need to stop the default behavior from being invoked.
    Let me explain a bit more about how event handling works. When you attach an event
    handler to an element, you can trigger JavaScript statements with the event. The JavaScript
    can return a result that is then passed back to the event handler. For example, you can
    attach some JavaScript to the onclick event of a link so that it returns a Boolean value of
    true or false. If you click on the link, and the event handler receives a value of true, it’s getting
    the message “yes, this link has been clicked.” If you add some JavaScript to the event
    handler so that it returns false, then the message being sent back is “no, this link has not
    been clicked.”
    You can see this for yourself with this simple test:
    <a href="http://www.example.com" onclick="return false;">Click me</a>
    If you click on that link, the default behavior will not be triggered, because the JavaScript
    is effectively canceling the default behavior.
    By adding a return false statement to the JavaScript contained by the onclick event
    handler, I can stop the user from being taken straight to destination of the link:

      onclick = "showPic(this); return false;"

    我们还想增加图片的说明文字,添加:

    <p id="description">Choose an image.</p>

    我们想要点击相应的图片时文件就会变为title的文字。

    怎么办?

    var text = whichpic.getAttribute("title");
    var description=document.getElementById("description");

    如果我们

     alert (description.nodeValue);

    结果会是null?

    This will return a value of null. The nodeValue of the paragraph element itself is empty.  What you actually want is the value of the text within the paragraph. The text within the paragraph is a different node. This text is the first child node of the paragraph. Therefore, you want to retrieve the nodeValue of this child node.
    This alert statement will give you the value you’re looking for:

        alert(description.childNodes[0].nodeValue);

    This will return a value of “Choose an image.” This means that you’re accessing the childNodes array and getting the value of the first element (index number zero).

    There is a shorthand way of writing childNodes[0]. Whenever you want to get the value
    of the first node in the childNodes array, you can use firstChild:
              node.firstChild
             This is equivalent to
          node.childNodes[0]
    This is a handy shortcut and it’s also a lot easier to read. The Document Object Model also provides a corresponding lastChild property:
             node.lastChild
    This refers to the last node in the childNodes array. If you wanted to access this node   without using the lastChild property, you would have to write
        node.childNodes[node.childNodes.length-1]

     

    Using nodeValue to update the description

        description.firstChild.nodeValue = text;

     现在我们不想用内联方式来增加onclick属性:

    function prepareGallery(){
        var gallery=document.getElementById("gallery");
        var links=gallery.getElementsByTagName("a");
        for(var i=0;i<links.length;i++)
        {
            links[i].onclick=function (){
                showPic(this);
                return false;
            }
        }
    }

    need to execute the prepareGallery function in order to attach the onclick events.
    If I simply execute the function right away, it won’t work.如果只是立即执行,并不会起作用。 If the JavaScript is executed  before the document has finished loading, the Document Object Model will be incomplete.
    By the third line of the function (the test for the existence of “imagegallery”), things
    won’t go according to plan.
    I want to execute the function only when the page has finished loading. When the page
    loads, an event is triggered. This event is onload and it is attached to the window object. If
    I attach the prepareGallery function to this event, then everything will go smoothly:
    window.onload = prepareGallery; 当页面载入时执行。(注意,后面没有())。

    如果想同时执行2个函数,怎么办?

    window.onload = firstFunction;
    window.onload = secondFunction;只会执行这个。

    secondFunction will replace firstFunction. On the face of it, you would think that an
    event handler can hold only one instruction.
    But here’s a workaround: I could create an anonymous function to hold the other two and
    then execute that third function when the page loads:

    window.onload = function() {
    firstFunction();
    secondFunction();
    }

    这个解决方案很简单,还有一种更好的方式。

    This function is called addLoadEvent, and it was written by Simon Willison
    (http://simon.incutio.com/). It takes a single argument: the name of the function that
    you want to execute when the page loads.
    Here’s what addLoadEvent does:
    1Stores the existing window.onload as a variable called oldonload.
    2If this hasn’t yet had a function attached to it, then simply add the new function in
    the usual way.
    3If there is already a function attached, add the new function after the existing
    instructions.

    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
    window.onload = func;
    } else {
    window.onload = function() {
    oldonload();
    func();
    }
    }
    }

    This effectively creates a queue of functions to be executed when the page loads. To add
    functions to this queue, I just need to write:
    addLoadEvent(firstFunction);
    addLoadEvent(secondFunction);

    DOM Core and HTML-DOM
    So far, I’ve been using a small set of methods to accomplish everything I want to do,
    including
    getElementById
    getElementsByTagName
    getAttribute
    setAttribute
    These methods are all part of the DOM Core. They aren’t specific to JavaScript, and they
    can be used by any programming language with DOM support. They aren’t just for web
    pages, either. These methods can be used on documents written in any markup language
    (XML, for instance).
    When you are using JavaScript and the DOM with (X)HTML files, you have many more
    properties at your disposal. These properties belong to the HTML-DOM, which has been
    around longer than the DOM Core.

    For instance, the HTML-DOM provides a forms object. That means that instead of writing:
    document.getElementsByTagName("form")
    You can use:
        document.forms
    Similarly, the HTML-DOM provides properties to represent attributes of elements. Images,
    for instance, have a src property. Instead of writing:
    element.getAttribute("src")
    You can write:


               element.src

    These methods and properties are interchangeable. It doesn’t really matter whether you
    decide to use the DOM Core exclusively or if you use the HTML-DOM. As you can see, the
    HTML-DOM is generally shorter. However, it’s worth remembering that it is specific to web
    documents, so you’ll need to bear that in mind if you ever find yourself using the DOM
    with other kinds of documents.

    If I were to use the HTML-DOM, I could shorten a few lines from the showPic function.
    This line uses the DOM Core to retrieve the href attribute of the whichpic element and
    assign its value to the variable source:
    var source = whichpic.getAttribute("href");
    Here’s the same thing using HTML-DOM:
    var source = whichpic.href;
    Here’s another example of the DOM Core. This time, the src attribute of the placeholder
    element is being set to the value of the variable source:
    placeholder.setAttribute("src",source);
    Here it is using HTML-DOM:
    placeholder.src = source;

     

  • 相关阅读:
    2018第45周日
    RabbitMQ消息的消费与持久化
    Rabbitmq的调度策略
    Rabbitmq交换器Exchange和消息队列
    RabbitMQ概念
    微服务拆分
    微服务演化
    2018第44周日
    福勒(Martin Fowler)
    微服务架构定义那点事
  • 原文地址:https://www.cnblogs.com/youxin/p/2653445.html
Copyright © 2011-2022 走看看