我正在尝试将数据属性的值分配给相同的元素srcset或src
var is_chrome = (typeof window.chrome === 'object' && navigator.appVersion.indexOf('Edge') === -1);
if ($('.image-browsers').length > 0) {
if (is_chrome) {
var a = $('.mobileImages').attr('data-mobileImage'),
b = $('.desktop-images').attr('data-mobileWebp');
$('.mobileImages').attr('srcset', a.val());
$('.desktop-images').attr('src', b.val());
}
else {
var c = $('.mobileImages').attr('mobileImage'),
d = $('.desktop-images').attr('desktopImage');
$('.mobileImages').attr('srcset', c.val());
$('.desktop-images').attr('src', d.val());
}
}
<picture class="image-browsers">
<isif condition="${mobileImage}">
<source class="mobileImages" srcset="" media="(max-width: 768px)" data-mobileImage="test.jpg" data-mobileWebp="test2.webp">
</isif>
<isif condition="${desktopImage}">
<img class="desktop-images" src="" alt="${'previewName' in contentAsset.custom && contentAsset.custom.previewName != null ? contentAsset.custom.previewName : '' }" title="${'previewName' in contentAsset.custom && contentAsset.custom.previewName != null ? contentAsset.custom.previewName : '' }"
data-desktopImage="test3.jpg" data-desktopWebp="test4.webp">
</isif>
</picture>
不确定我要去哪里。如果我删除val(),没有错误。如果添加它,它会显示错误。
答案 0 :(得分:0)
我建议使用data(...)函数。
.data(...)函数返回一个不是HTML元素的对象(在这种情况下为字符串),因此没有val方法。看jQuery data
.attr(...)函数返回字符串类型的对象,但没有“ val”方法。 jQuery attr
答案 1 :(得分:0)
这有效:
if (is_chrome) {
var a = $('.mobileImages').attr('data-mobileWebp'),
b = $('.desktop-images').attr('data-desktopWebp');
$('.mobileImages').attr('srcset', a);
$('.desktop-images').attr('src', b);
}
else {
var c = $('.mobileImages').attr('data-mobileImage'),
d = $('.desktop-images').attr('data-desktopImage');
$('.mobileImages').attr('srcset', c);
$('.desktop-images').attr('src', d);
}
不确定为什么不起作用:
if (is_chrome) {
var a = $('.mobileImages').data('mobileWebp'),
b = $('.desktop-images').data('desktopWebp');
$('.mobileImages').attr('srcset', a);
$('.desktop-images').attr('src', b);
}
else {
var c = $('.mobileImages').data('mobileImage'),
d = $('.desktop-images').data('data-desktopImage');
$('.mobileImages').attr('srcset', c);
$('.desktop-images').attr('src', d);
}