gpt4 book ai didi

javascript - 未捕获的 ReferenceError : foo is not defined at HTMLAnchorElement. onclick?

转载 作者:行者123 更新时间:2023-11-30 15:23:41 25 4
gpt4 key购买 nike

我在 jquery.Ajax 函数中操作 json 数组。语法让我很困惑,所以我找不到这个错误。我在做什么 我将点击功能绑定(bind)到 anchor 标记,然后当我点击该 anchor 标记并调用 foo() 函数时,出现此错误 UncaughtReferenceError : foo is not defined at HTMLAnchorElement.onclick

  function show(thelink)
{

var cat = thelink.innerHTML;
var productContainer = document.getElementById("productContainer");

$.ajax({

type:"POST",
url:"fetchdata1",
data:"cat="+cat,

success:function(data){
productContainer.innerHTML ="";
var $productContainer = $('#productContainer');
$.each(data,function(key,value){
if(value['newVar'] === 1)
{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
<br/><br/><a href='#' onclick='foo(this)' pid='"+value['id']+"'>REMOVE</a></div>");

}
else{

$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span></div>");
}
}) ;

}

});


function foo(obj){

var pid = $(obj).attr("pid");
$(obj).bind("click", function(){

$.ajax({

type:"POST",
url:"removeFromWishlist",
data:"pid="+pid,

success:function(response){

}


});



});

}


return false;
}

最佳答案

这里的问题是您在 show 函数中定义了函数 foo,因此它只能从 show 范围访问。

因此,当您在 HTML 中使用 onclick='foo(this)' 时,您指的是 window 全局中的 foo 函数范围,所以这就是你得到的原因:

UncaughtReferenceError : foo is not defined at HTMLAnchorElement.onclick

您需要将函数 foo 声明移到 show 函数之外,以便可以从 window 全局范围访问它。

关于javascript - 未捕获的 ReferenceError : foo is not defined at HTMLAnchorElement. onclick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43307774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com