![](/img/trans.png)
[英]Why aren't the links I'm adding to the DOM with Javascript clickable?
[英]Isotope & javascript - elements aren't clickable anymore after adding a new one
我正在尝试制作一个从json(不是真正的json,更像是一个javascript数组)加载的图像表,每次json更改时(当我用一些脚本将新图像附加到json文件时,我想要那个我上传的图片表也是如此。
这是json格式:
[{
"image": "images/set_1_UTC+03.jpg",
"weight": 101
}, {
"image": "images/set_1_UTC+03.jpg",
"weight": 102
}, {
"image": "images/set_1_UTC+03.jpg",
"weight": 103
}, {
"image": "images/set_1_UTC+03.jpg",
"weight": 104
}]
为此,我使用同位素。 我设法实现了上面提到的所有内容,唯一的问题是我想让图像可以点击,每当我点击其中一个图像时,让它的尺寸更大,当我再次点击它以回到小尺寸。 这是代码:
<script>
var previous = 0;
var current = 0;
loadJSON(function(response) {
// Parse JSON string into object
current = JSON.parse(response);
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
let lengthOfprevious = previous.length;
setInterval(function() {
loadJSON(function(response) {
// Parse JSON string into object
current = JSON.parse(response);
});
previous = current;
if (lengthOfprevious != current.length) {
UpdateBody(lengthOfprevious);
}
lengthOfprevious = previous.length;
}, 5000);
function UpdateBody(startIndex) {
var newElements = "";
for (let i = startIndex; i < previous.length; i++) {
$(document).ready(function() {
newElements = "";
newElements +=
'<div class="photo element-item">' +
'<a href="' + previous[i].image + '"><img class="small-image" src="' + previous[i].image + '"/></a>' +
'<a class="weight">' + previous[i].weight + '</a></div>';
var $newElems = $(newElements);
$('#container').append($newElems).imagesLoaded(function() {
$('#container').isotope('insert', $newElems);
});
});
}
// ============//
$(function() {
var $container = $('#container'),
$photos = $container.find('.photo'),
$loadingIndicator = $('<div class="loading"><span><img src="http://i.imgur.com/IE7iw.gif" /></span></div>');
// trigger Isotope after images have loaded
$container.imagesLoaded(function() {
$container.isotope({
itemSelector: '.photo',
masonry: {
columnWidth: 200
}
});
});
// shows the large version of the image
// shows small version of previously large image
function enlargeImage($photo) {
$photos.filter('.large').removeClass('large');
$photo.addClass('large');
$container.isotope('reLayout');
}
$photos.find('a').click(function() {
var $this = $(this),
$photo = $this.parents('.photo');
if ($photo.hasClass('large')) {
// already large, just remove
$photo.removeClass('large');
$container.isotope('reLayout');
} else {
if ($photo.hasClass('has-big-image')) {
enlargeImage($photo);
} else {
// add a loading indicator
$this.append($loadingIndicator);
// create big image
var $bigImage = $('<img>', {
src: this.href
});
// give it a wrapper and appended it to element
$('<div>', {
'class': 'big-image'
})
.append($bigImage)
.appendTo($this)
.imagesLoaded(function() {
$loadingIndicator.remove()
enlargeImage($photo);
});
// add a class, so we'll know not to do this next time
$photo.addClass('has-big-image');
}
}
return false;
});
});
}
</script>
问题是setInterval运行一次后,一切都按预期工作,再次运行时,图像不再可点击。 如果我在for中删除// ============ //标签后的部分,则只能点击最后一个图像。
我无法找到解决方案(我是javascript的初学者)。 有人能指出我正确的方向吗?
更新 : 在这里,您可以获得项目的存档,以便可以在本地运行它。
您需要手动复制并粘贴数据文件中的某些行以使演示工作,因为它会搜索先前状态与数据文件当前状态的差异。 问题是它最初是可点击的,然后它就不再存在了。
我在你的代码中发现了一些需要修改的东西:
$(document).ready
使用了超过1次? $(function()
因为我看到照片类是在运行时动态生成的,而容器类已经在DOM中,所以我修改了click事件
$container.on('click', '.photo a', function() {
编辑请注意代码未经过测试; 我刚刚修改了代码。
最终更新的代码如下:
var previous = 0;
var current = 0;
loadJSON(function(response) {
// Parse JSON string into object
current = JSON.parse(response);
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
let lengthOfprevious = previous.length;
setInterval(function() {
loadJSON(function(response) {
// Parse JSON string into object
current = JSON.parse(response);
});
previous = current;
if (lengthOfprevious != current.length) {
UpdateBody(lengthOfprevious);
}
lengthOfprevious = previous.length;
}, 5000);
function UpdateBody(startIndex) {
var newElements = "",
$container = $('#container'),
$photos = $container.find('.photo'),
$loadingIndicator = $('<div class="loading"><span><img src="http://i.imgur.com/IE7iw.gif" /></span></div>');
$(document).ready(function() {
for (let i = startIndex; i < previous.length; i++) {
newElements = "";
newElements +=
'<div class="photo element-item">' +
'<a href="' + previous[i].image + '"><img class="small-image" src="' + previous[i].image + '"/></a>' +
'<a class="weight">' + previous[i].weight + '</a></div>';
var $newElems = $(newElements);
$container.append($newElems).imagesLoaded(function() {
$container.isotope('insert', $newElems);
});
}
$container.imagesLoaded(function() {
$container.isotope({
itemSelector: '.photo',
masonry: {
columnWidth: 200
}
});
});
// shows the large version of the image
// shows small version of previously large image
function enlargeImage($photo) {
$photos.filter('.large').removeClass('large');
$photo.addClass('large');
$container.isotope('reLayout');
}
$container.on('click', '.photo a', function() {
var $this = $(this),
$photo = $this.parents('.photo');
if ($photo.hasClass('large')) {
// already large, just remove
$photo.removeClass('large');
$container.isotope('reLayout');
} else {
if ($photo.hasClass('has-big-image')) {
enlargeImage($photo);
} else {
// add a loading indicator
$this.append($loadingIndicator);
// create big image
var $bigImage = $('<img>', {
src: this.href
});
// give it a wrapper and appended it to element
$('<div>', {
'class': 'big-image'
})
.append($bigImage)
.appendTo($this)
.imagesLoaded(function() {
$loadingIndicator.remove()
enlargeImage($photo);
});
// add a class, so we'll know not to do this next time
$photo.addClass('has-big-image');
}
}
return false;
});
});
}
您可以使用以下脚本块替换脚本块并尝试运行:
<script>
var previous = [];
var current = [];
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function start(){
loadJSON(function(response) {
previous = current;
current = JSON.parse(response);
if (previous.length != current.length) {
UpdateBody(current);
}
});
}
function UpdateBody(data) {
var newElements = "";
for (var i in data) {
newElements +=
'<div class="photo element-item">' +
'<a href="' + data[i].image + '"><img class="small-image" src="' + data[i].image + '"/></a>' +
'<br/>' +
'<a class="weight">' + data[i].weight + '</a>' +
'</div>';
}
if(newElements!=""){
var $newElems = $(newElements);
$('#container').append($newElems).imagesLoaded(function() {
$('#container').isotope('insert', $newElems);
});
}
}
$(document).ready(function(){
start();
setInterval(start, 5000);
var $container = $('#container'),
$photos = $container.find('.photo'),
$loadingIndicator = $('<div class="loading"><span><img src="http://i.imgur.com/IE7iw.gif" /></span></div>');
// trigger Isotope after images have loaded
$container.imagesLoaded(function() {
$container.isotope({
itemSelector: '.photo',
masonry: {
columnWidth: 200
}
});
});
// shows the large version of the image
// shows small version of previously large image
function enlargeImage($photo) {
$container.find('.photo.large').removeClass('large');
$photo.addClass('large');
$container.isotope('layout');
}
$(document).on('click','#container .photo a',function() {
var $this = $(this),
$photo = $this.parent('.photo');
if ($photo.hasClass('large')) {
// already large, just remove
$photo.removeClass('large');
$container.isotope('layout');
} else {
if ($photo.hasClass('has-big-image')) {
enlargeImage($photo);
} else {
// add a loading indicator
$this.append($loadingIndicator);
// create big image
var $bigImage = $('<img>', {
src: this.href
});
// give it a wrapper and appended it to element
$('<div>', {
'class': 'big-image'
})
.append($bigImage)
.appendTo($this)
.imagesLoaded(function() {
$loadingIndicator.remove()
enlargeImage($photo);
});
// add a class, so we'll know not to do this next time
$photo.addClass('has-big-image');
}
}
return false;
});
});
</script>
我在你的代码上改变了很多东西。 这帮我组织了代码。 但点击不起作用的最重要部分如下:
$(document).on('click','#container .photo a',function() {
我附上了如上所述的click事件处理程序,因为在页面加载后会添加元素。 因此它需要使用稍后添加处理程序时添加的元素。
您可以阅读有关jQuery.on
函数的更多信息,并尝试了解它是如何工作的。
$photos.find('a').click(
- 这个绑定点击现有的项目,所以新的它不会触发点击。你应该事件委托&
$('.items_wrap_class').on('click', 'a', function() { /* all existings an new items clicks will fire this */ })
UPD
在你的情况下,请委托#container
.photo a
点击处理。
替换$photos.find('a').click( function() { ... })
同
$('#container').on('click', '.photo a', function() { ... })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.