javascript - 无法更改 js 代码。如何在js循环中调用函数或编写函数
问题描述
我正在制作一个电子商务网站。
https://colorlib.com/wp/template/onetech/在这个主题中,我正在编写自己的 php 代码并更改一些 js。但我面临一个问题,不知道如何解决这个问题。我的html代码是
<div class="product_fav"><i class="fas fa-heart"></i></div>
,js是`
function initFavs()
{
var fav = $('.product_fav');
fav.on('click', function()
{
fav.toggleClass('active');
});
}`
我将此html代码更改为
<div class="product_fav"><i class="pro fas fa-check"></i></div> <span id="txtHint"></span>
和 js 到`
function initFavs()
{
var fav = $('.product_fav');
var faav = $('.pro');
faav.on('click', function()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("wili").innerHTML = this.responseText;
}
};
if(faav.hasClass('fa-times'))
{
faav.removeClass('fa-times');
faav.addClass('fa-check');
fav.toggleClass('active');
fav.removeClass('deactive');
xhttp.open("GET", "addfavorite.php?no=" + no + "&id=" + id + "", true);
xhttp.send();
xxhttp.open("GET", "totalfavorite.php?no=" + no + "", true);
xxhttp.send();
}
else if(faav.hasClass('fa-check') && fav.hasClass('active'))
{
faav.addClass('fa-times');
faav.removeClass('fa-check');
fav.toggleClass('deactive');
fav.removeClass('active');
xhttp.open("GET", "removefavorite.php?no=" + no + "&id=" + id + "", true);
xhttp.send();
xxhttp.open("GET", "totalfavorite.php?no=" + no + "", true);
xxhttp.send();
}
else if(faav.hasClass('fa-check'))
{
faav.removeClass('fa-times');
faav.addClass('fa-check');
fav.toggleClass('active');
fav.removeClass('deactive');
xhttp.open("GET", "addfavorite.php?no=" + no + "&id=" + id + "", true);
xhttp.send();
xxhttp.open("GET", "totalfavorite.php?no=" + no + "", true);
xxhttp.send();
}
});
}`
对于此页面http://shop.virusincbd.com/product.php 但我无法转换此代码(html 相同)`
function initFavs()
{
// Handle Favorites
var items = document.getElementsByClassName('product_fav');
for(var x = 0; x < items.length; x++)
{
var item = items[x];
item.addEventListener('click', function(fn)
{
fn.target.classList.toggle('active');
});
}
}`
解决方案
您需要从 更改$('.pro').on('click'
为$('.product_fav').on('click'
这是工作示例:
推荐阅读
- terraform - 如何强制 Cloudfront 将来自源的所有请求强制为 HTTPS?
- zarr - 是否可以在单个文件中存储多个组和数组?
- javascript - 了解使用 new 关键字后如何使用方法
- django - 使我的 Kivy 移动应用程序能够使用套接字(用于实时消息传递文本和图像)到/来自 Django 后端
- c# - Unity ScriptedImporter AssetImporters 在构建时的命名空间“UnityEditor”中不存在
- javascript - Python 和 Flask:帮助在一个 @app.route 下组合 Add 和 Remove
- python - 为什么我的 .tiff 文件不能转换并保存为 .jpeg
- c++ - 填充数组数组
- php - 重定向 URL 中缺少斜杠
- javascript - 从 MongoDB 中的单个集合中获取每个文档