![](/img/trans.png)
[英]How can I get a list element to be “toggled” (JQuery) and then when this animation is done removed(), all upon a mouse click of the img in the <li>?
[英]I can't get my Jquery to work: Need to add img tag dynamically upon click
對於下面的代碼,當您單擊按鈕時,我試圖獲取一個img標簽以加載到頁面上的某處。 這只是出於測試目的,但我需要使其正常工作。 img標簽是一個1乘1像素,用於跟蹤單擊了某些內容。 我知道一個標簽會更適合於此目的,但是由於我在這里無法解釋的原因,無法使用它。
您可以提供任何建議以使以下代碼正常工作。 我將在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');
});
});
我不是即時制作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中。 這種方法(而不是寫一個大的長字符串)是很好的,因為它可以使所有內容保持整潔-不必擔心轉義引號,並且在其中為某些屬性添加動態值將非常容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.