我可以'我的Jquery无法正常工作:需要在单击时动态添加img标记

I can't get my Jquery to work: Need to add img tag dynamically upon click

本文关键字:单击 标记 img 添加 动态 工作 我的 Jquery 常工作 我可以      更新时间:2023-09-26

对于下面的代码,我试图在您单击按钮时在页面上的某个位置加载img标记。这只是为了测试目的,但我需要让它发挥作用。img标记是一个1乘1的像素,用来跟踪点击了什么。我知道a标记更适合这个目的,但由于我无法在这里解释的原因,不能使用它。

您可以为以下代码的运行提供任何建议。我将在Fiddler测试以确认。

如果您需要更多信息或澄清,请告诉我。

我感谢你的帮助!

谢谢,

<html>
<style type="text/css">
#button {
    display: inline-block;
    height: 20px;
    width: 150px;
    background-color:orange;
    font-family:cursive, arial;
    font-weight:bold;
    color: brown;
    border-radius:5px;
    text-align:center;
    margin-top:2px;
}
#output {
    font-family:garamond;
    color:black;
    height:450px;
    width:320px;
    border-radius:2px;
    border-color:black;
    background-color:white;
    overflow: auto;
    float: left;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
 $('#button').click(function(){
  document.getElementById('output').innerHTML +=('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
 });
});
</script>
<body>
<div id="button">Test</div>
<div id="output"></div>
</body>
</html>

替换此:

$(document).ready(function() {
 $('#button').click(function(){
  document.getElementById('output').innerHTML +=('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
 });
});

有了这个:

$(document).ready(function() {
    $('#button').click(function(){
        $('#output').append('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
    });
});

每次单击时,使用.append("<img..)将添加另一个img。如果这不是你所期望的,那么编辑你的问题,详细说明你希望它如何工作。

$('#output').prepend('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
$(function() {
    $('#button').on('click',function(e) { //.on() preferred, click() is a short-hand for this
        e.preventDefault(); //if you change from div to `A` someday
        var timestamp = Math.round(new Date().getTime() / 1000);
        //creating IMG on-the-fly, adding css and appending it
        $('<img />', {
            'src': 'http://view.atdmt.com/action/AAA_ImageTest?ts='+timestamp
        }).css({
            'width':'1px',
            'height':'1px', 
            'border':0
        }).appendTo('#output');     
    });
});

我不是在had上制作HTML并添加为HTML,而是动态创建img,添加它的CSS并附加到#output

e.preventDefault它只是用于阻止项目的默认行为。如果有一天你从<div id="button">Test</div>变成了一个真正的主播<a id="button" href="#">Test</a>,那只是一个额外的奖励。

更新:@Kamui为了防止图像缓存(因此在添加另一个时不会进行第二次调用),我在图像URL上添加了一个时间戳。

如果您想附加纯jQuery方式:

jQuery("#output").append(
    jQuery("<img>")
        .attr("height", "1")
        .attr("width", "1")
        .attr("src", "http://view.atdmt.com/action/AAA_ImageTest")
);

这将在jQuery世界中创建一个img对象,然后将其附加到您的输出div中。这种方法(而不是写一个大的长字符串)很好,因为它可以保持所有内容的干净-不用担心转义引号,并且可以很容易地在其中为某些属性添加动态值。