【问题标题】:Value not passing properly in javascript function while iterator using $.each() function使用 $.each() 函数的迭代器时,值未在 javascript 函数中正确传递
【发布时间】:2015-07-03 12:57:01
【问题描述】:

我从 Ajax 调用返回一个名为“categories”的对象数组,然后我在字符串(categoriesList)中替换它的对象(category)值。然后我将 html div 区域中的这个字符串替换为$("#divAreaName").html("StringName");

为了正确理解,代码如下所示:

$.each(categories,function(index,category){
    categoriesList = categoriesList + 
    "<div class='media'>"+
        "<img onclick=dispProductCategoryWise('"+category.name+"','"+category.id+"','"+id+"','"+retailerId+"'); src='${pageContext.request.contextPath}"+category.image+"'>"+
    "</div>"+
    "<div class='item-info'>"+
        "<div class='item-name item-row'>"+
            "<span class='full-item-name'>"+category.name+"</span>"+
        "</div>"+
    "</div>";
}); 

然后我使用以下代码行替换 div 区域中的字符串

$("#divName").html(categoriesList);

但是问题在于 category.name 是“Fruits and Vegetable”时。 HTML形成如下图:

<img onclick="dispProductCategoryWise('Fruits" &="" Vegetable','60','1','2');="" src="/closerby/images/customer/category/FandV.jpeg">

有人可以告诉我为什么这些值没有正确传递以及可能的解决方案吗?

【问题讨论】:

  • 添加有问题的categories 数组
  • 可能的解决方案是什么?
  • 我认为您的 "&lt;img onclick=dispProductCategoryWise( 缺少 onclick 属性值的开头引号,而且 onclick 属性后的分号是什么

标签: javascript jquery html arrays ajax


【解决方案1】:

有趣的问题,似乎在使用.html() 时,空格被奇怪地转换了。好像 '/" 本身被渲染了。 console.log 也给出了正确的字符串。

或者,使用动态生成的 id 在该特定图像上创建一个事件。

像这样:

categories = {
        "category":{
            "name": "Fruits and Vegetables",
            "id": 1,
        }
    }

    $.each(categories,function(index,category){
        categoriesList = 
        "<div class='media'>"+
            "<img id='specific_"+index+"' src='{somethingwashere}'>"+
        "</div>"+
        "<div class='item-info'>"+
            "<div class='item-name item-row'>"+
                "<span class='full-item-name'>"+category.name+"</span>"+
            "</div>"+
        "</div>";
        $("#myDiv").html(categoriesList);
        //Added event.
        $('#specific_'+index).click(function() {
            return displayProductCategoryWise(category.name, category.id);  
        });
    }); 

    function displayProductCategoryWise(name, id) {
        alert(name);
        alert(id);
    }

【讨论】:

    【解决方案2】:

    我只使用$('selector').each(fn) 为每个匹配的 jquery 元素做一些事情

    或许可以试试categories.forEach(function(category, index){ ...

    【讨论】:

    • 我用过 $.each(categories,function(index,category){ });它正在迭代数组列表的每个对象。问题出在替换对象的值的时候。
    • 尽管我也会尝试你的方法并回复你
    【解决方案3】:

    你是在把引号变成特殊字符吗.....添加一个黑斜线()

    类似:

    <img onclick=dispProductCategoryWise('\"+category.name+\"','\"+category.id+\"','\"+id+\"','\"+retailerId+\"'); src='${pageContext.request.contextPath}\"+category.image+\"'>\"
    

    【讨论】:

    • 其实更糟
    猜你喜欢
    • 2011-08-24
    • 2012-10-19
    • 2019-12-23
    • 2015-04-15
    • 2020-10-28
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多