【问题标题】:Change the value of "data-image" attribute更改“data-image”属性的值
【发布时间】:2019-01-21 01:30:35
【问题描述】:

我想使用 switch 和 jquery 在多个 div 中动态显示不同的图像。
我必须在data-image="" 中添加图像。

这是我的代码:

 <div class="tb-image-carte" aria-hidden="true">
    <div data-image="" class="--contain"></div>
 </div>
 <div class="tb-image-carte" aria-hidden="true">
    <div data-image="" class="--contain"></div>
 </div>
 <div class="tb-image-carte" aria-hidden="true">
    <div data-image="" class="--contain"></div>
 </div>

这是我的 javascript 代码:

var imageCarte = $('data-image');
    res.forEach(function(image) {
      switch (image.imageCode) { 
        case "1":
        case "2": 
        imageCarte = "the beach" 
        break
        case "3":
        case "4": 
        imageCarte = "home" 
        break
      }
    });

我想根据条件给每个data-image加一个值

【问题讨论】:

    标签: jquery switch-statement


    【解决方案1】:

    您需要改用 jQuery .data() 方法:

    var imageCarte = $('div[data-image]');
    
    res.forEach(function(image) {
      switch (image.imageCode) { 
        case "1":
        case "2": 
            imageCarte.data("image", "the beach");
        break
        case "3":
        case "4": 
            imageCarte.data("image", "home");
        break
      }
    });
    

    【讨论】:

    • 非常感谢您的回答,它仍然不起作用,但我一直在寻找您写的内容:)
    【解决方案2】:

    您可以只使用attr() 函数:

    $(".tb-image-carte>div">.attr("data-image","newattrdata");
    

    我建议在图像 div 中添加一个 ID 以避免错误,或者至少在选择类时更加清晰:

    <div data-image="" class="--contain" id="image1"></div>
    
    //SO yo can do:
    $("#image1").attr("data-image","new Data image");
    

    【讨论】:

    • @Cristian69 非常感谢,您的第一个解决方案效果很好。但你是对的,我会添加 ID。您只是在代码中忘记了一个小括号:)
    • 更确定,因为如果你有 2 个 tb-image-carte 元素,attr 将在两者中都发生变化
    • 但是,如果我必须多次放置同一个 div,它不会显示所有图像,因为我知道我不应该为每个 div 添加不同的 id。我编辑了我的问题
    • @mathiasF 你想把同一张图片放在所有 3 个 div 中??
    • 不,我希望每个div中的图像根据切换条件动态显示。目前它会显示在我获得的对象列表中找到的最后一张图片。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多