如何使用jquery .html()方法将div的内容设置为另一个div

时间:2014-01-28 11:46:30

标签: jquery html css

这里我有一些链接<a href> s,这些href链接到div。当我点击链接时,链接的div内容应该出现在另一个div

为此我尝试使用jquery的.html()方法。 首先,我试图获取被点击的div的id。并从该id获取该div的内容,并将div的内部内容设置为dispfe div。但它不起作用......

我该怎么做?

代码:

<!DOCTYPE html>
<html>
<head>
<title>InnerHtml</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

<script>
$(document).ready(function() {
    $("a").click(function(event) {
        var $td = $(event.target.id);
        alert($td);
    });
});
</script>


</head>
<body>

             <a href="#d1" id="f1">Head Light</a><br /> 
             <a href="#d2" id="f2">Hood</a> <br />
             <a href="#d3" id="f3">Wind-shield</a><br /> 
             <a href="#d4" id="f4">Rear wheels</a> <br />
             <a href="#d5" id="f5">Sun roof</a> <br />
             <a href="#d6" id="f6">Front wheels</a> <br />
             <a href="#d7" id="f7">Front hoop</a> <br />
             <a href="#d8" id="f8">Rear mirrors</a> <br />
             <a href="#d9" id="f9">Finishing</a> <br />


    <div id="d1" style="display:none;"> A headlamp is a lamp attached to the front of a     </div>

    <div id="d2" style="display:none;"> he hood bonnet is the hinged cover over the engine  </div>

    <div id="d3" style="display:none;"> The windshield or windscreen of an aircraft, car, bus, </div>

    <div id="d4" style="display:none;"> In automotive design, the automobile layout describes   </div>

    <div id="d5" style="display:none;"> Lorem Ipsum is simply dummy text of the printing </div>

    <div id="d6" style="display:none;"> The term motorcar has formerly also been used </div>

    <div id="d7" style="display:none;"> The weight of a car influences fuel consumption </div>

    <div id="d8" style="display:none;"> Most cars are designed to carry multiple occupants</div>

    <div id="d9" style="display:none;"> Mary Ward became one of the first documented </div>

<br />



<div class="dispfe" style="width:40%;height:400px;border:solid black 1px;">

</div>


</body>
</html>

4 个答案:

答案 0 :(得分:1)

<script>
$(document).ready(function() {
    $("a").click(function(event) {
        var href = $(event.target.id);
        $(".dispfe").html($(href).html());
    });
});
</script>

答案 1 :(得分:1)

使用此

var href = $(this).attr('href');
alert(href);

答案 2 :(得分:1)

而不是href="#d8使用data-href="d8"和jQuery:

$('a[data-href]').click(function(e) {
  e.preventDefault();
  var $target = $('#' + $(this).attr('data-href'));
  $('#d1').html(target.html());
});

答案 3 :(得分:1)

$(document).ready(function() {
        $("a").click(function(event) {
            $(".dispfe").html($($(this).attr('href')).html());
        });
    });

演示FIDDLE