【问题标题】:js passing a variable to a function returning undefinedjs将变量传递给返回未定义的函数
【发布时间】:2015-04-12 01:07:07
【问题描述】:

我正在尝试将使用动态内容创建的变量传递给 Javascript 中的函数。唯一的问题是在控制台中它返回未定义,但它的未定义与传递的值

Uncaught ReferenceError: zukeru is not defined profile.html:1 onclick

代码:

function getFriend(friend){
  console.log(friend,toString());
  document.cookie = "getuser="+friend;
  window.location="profile.html";  // change url to your's
}


function getFriendlist(){
    var profile_pic_friend = '';
    var flist = Cynergi.get('http://:3000/friends?my_username=eq.' + get_user);
    var flist_html = 'Friends: ';
    $.each(flist, function(i, item) {

        var profile_pic_ret = Cynergi.get('http://:3000/profile_pictures?username=eq.' + item.friend_username );
      $.each(profile_pic_ret, function(i, item) {
        profile_pic_friend = item.pic_location;
      });

        flist_html = flist_html + "<div><a onclick='getFriend("+item.friend_username+");'><img width='100' height='100' src='"+ profile_pic_friend + "'><br>" + item.friend_username + "</a></div>"
    });
    $("#flist").html(flist_html);
    setTimeout(function() { getFriendlist(); }, 1000);
}
getFriendlist();

【问题讨论】:

  • 在 html 属性中使用 JSON.stringify(item.friend_username) 而不仅仅是 item.friend_username
  • 在发布的代码中zukeru 在哪里?
  • @adeneo 是的,它是发送到函数的值,这是我没有得到的。

标签: javascript jquery html


【解决方案1】:

之所以失败是因为item.friend_username是一个字符串,所以当你生成这样的链接时:

flist_html = flist_html + "<div><a onclick='getFriend("+item.friend_username+");'><img width='100' height='100' src='"+ profile_pic_friend + "'><br>" + item.friend_username + "</a></div>"

您缺少引号来指定它是一个字符串。由于您没有用引号包裹该值,因此浏览器知道您传递的是一个变量(在您的情况下为 zukeru),它会因为未定义而失败。

要解决此问题,请将变量值用引号括起来(对于这种特殊情况,您需要对它们进行转义),问题将得到解决:

flist_html = flist_html + "<div><a onclick='getFriend(\""+item.friend_username+"\");'><img width='100' height='100' src='"+ profile_pic_friend + "'><br>" + item.friend_username + "</a></div>"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多