![](/img/trans.png)
[英]Javascript : How to make a element clickable that was created in a function
[英]How to make a thumbnail created by a function clickable in html?
我正在嘗試在HTML代碼中創建可點擊的縮略圖,但我不知道該怎么做。 我知道<a href = "">
無法正常工作。 如何使每個縮略圖都可單擊,以便將其定向到另一個頁面?
這是我用來從數據庫獲取數據並創建縮略圖的函數。
<script>
$(function(){
$.ajax({
url: '/getMovies',
type: 'GET',
success:function(response) {
console.log(response);
var data = JSON.parse(response);
var itemsPerRow = 0;
var div = $('<div>').attr('class','row');
for(var i=0;i<data.length;i++){
console.log(data[i].Title);
if(itemsPerRow<3){
console.log(i);
if(i==data.length-1){
div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
$('.well').append(div);
}
else{
div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
itemsPerRow++;
}
}
else{
$('.well').append(div);
div = $('<div>').attr('class','row');
div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
if(i==data.length-1){
$('.well').append(div);
}
itemsPerRow = 1;
}
}
},
error:function(error){
console.log(error);
}
});
});
})
function CreateThumb(id,name,type,copies){
var mainDiv = $('<div>').attr('class','col-sm-4 col-md-4');
var thumbNail = $('<div>').attr('class','thumbnail');
var caption = $('<div>').attr('class','caption');
var title = $('<h3>').text(name);
var title = $('<h5>').text(type);
var title = $('<h4>').text(copies);
var p = $('<p>');
caption.append(name);
caption.append(p);
caption.append(type);
thumbNail.append(caption);
mainDiv.append(thumbNail);
return mainDiv;
}
</script>
`。
添加縮略圖后,請使用:
$(".thumbnail").onclick(function(){
document.location.href = newUrl;
}
您可以使用jQuery來監聽點擊:
// Change the selector used below
$('#some-id-here').click(function(){
// Your code here
});
還有另一種方法,使用“ on”。 這可能對您更有用,因為它還會觸發動態添加到頁面的項目,這似乎是您的情況。
// Change the selector used below
$('#some-id-here').on('click', 'img', function(){
// Your code here.
});
另外,您可以選擇帶有$(document)
(而不是#some-id-here
)將其全局應用到頁面上,因此每個img
標簽都會觸發此功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.