网址上的JQuery点击更改图片

时间:2015-10-20 23:04:55

标签: jquery image

我有这个HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Gallery</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="image_gallery.js"></script>
</head>
<body>
<section>
<h1>Image Gallery</h1>
<ul id="image_list">
    <li><a href="images/casting1.jpg" title="Casting on the Upper Kings">Upper Kings</a></li>
    <li><a href="images/casting2.jpg" title="Casting on the Lower Kings">Lower Kings</a></li>
    <li><a href="images/catchrelease.jpg" title="Catch and Release on the Big Horn">Big Horn</a></li>
    <li><a href="images/fish.jpg" title="Catching on the South Fork">South Fork</a></li>
    <li><a href="images/lures.jpg" title="The Lures for Catching">Lures</a></li>
</ul>
<h2 id="caption">Casting on the Upper Kings</h2>
<p id="gallery">
    <img src="images/casting1.jpg" alt="Image Gallery area" id="image">
</p>
</section>
</body>

如何将p id =“gallery”的图像更改为在ul id =“image_list”和标题中点击的链接的href?

我有这个Jquery:

$(document).ready(function () {

$(function () {
    $("li").click(function () {
        var imgUrl = $(this).find("href").attr("src"); //gets href
        var title_desc = $(this).text(); //gets title

        $('#image_list').click(function (e) {
            e.preventDefault();  //disables the heperlink
            $('#caption').replaceWith(title_desc); //changes the title
            $("#image").attr("src", imgUrl) //changes the href
        });
    })
});
});

此代码更改了内容,但未找到图像,替换和标题消失。比如获取图像和标题是错误的

2 个答案:

答案 0 :(得分:1)

$('#image_list li a').click(function(){
    imgUrl = $(this).attr('href');
    title_desc = $(this).attr('title');

    $('#caption').text(title_desc);
    $('#image').attr('src', imgUrl);

    return false;
});

答案 1 :(得分:0)

选择太多,您无需在点击事件中调用click()。我建议这样做:

http://jsfiddle.net/Twisty/59m6p1qw/

$(document).ready(function(){
    $("#image_list a").click(function (e) {
        e.preventDefault();
        var imgUrl = $(this).attr("href"); //gets href value
        var title_desc = $(this).attr("title"); // gets the title value
        $('#caption').html(title_desc); //changes the title
        $("#image").attr("src", imgUrl) //changes the source
    });
});