简体   繁体   中英

How do you put links inside of the jQuery .html() function

I am trying to make a single page poetry page that flips between poems by replacing the content inside of the elements. The problem that I have is with replacing the image link because Javascript marks the double slash "//" as comment so it makes the link break. Is there a way to set any variables to be the entire img tag along with the link inside?

function loadDreams() {
      $("h2").html("Dreams");
      $("h3").html("by Langston Hughes");
      $("p").html("Hold fast to dreams<br>For if dreams die<br>Life is a broken-winged bird<br>That cannot fly.<br><br>Hold fast to dreams<br>For When dreams go<br>Life is a barren field<br>Frozen with snow.<br>");
      $("div").html("<img src="http://3.bp.blogspot.com/-8cbVCg0AU3I/Tz19x0To6bI/AAAAAAAABCA/evbuLgR4bu4/s400/3junco3.jpg" class="image">");
    }

The issue is that you're opening your JavaScript string literal with double-quotes, then inadvertently closing the string with the src attribute double-quotes. It's fine to have // as long as it's inside a string literal.

It's best to use something like single quotes for your JS strings so that the HTML double quotes can peacefully coexist inside. (or use double quotes for the JS and single quotes for HTML... just don't mix).

$("div").html("<img src='http://3.bp.blogspot.com/-8cbVCg0AU3I/Tz19x0To6bI/AAAAAAAABCA/evbuLgR4bu4/s400/3junco3.jpg' class='image'>");

Singular quote things inside the html("") should do it. At the moment you're actually breaking out after "< img src="

Instead of wrapping your <img... /> in double quotes, use single quotes:

function loadDreams() {
    $("h2").html("Dreams");
    $("h3").html("by Langston Hughes");
    $("p").html("Hold fast to dreams<br>For if dreams die<br>Life is a broken-winged bird<br>That cannot fly.<br><br>Hold fast to dreams<br>For When dreams go<br>Life is a barren field<br>Frozen with snow.<br>");
    $("div").html('<img src="http://3.bp.blogspot.com/-8cbVCg0AU3I/Tz19x0To6bI/AAAAAAAABCA/evbuLgR4bu4/s400/3junco3.jpg" class="image">');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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