gpt4 book ai didi

javascript - 如果动态元素通过条件,则更改其属性

转载 作者:行者123 更新时间:2023-12-01 03:48:29 25 4
gpt4 key购买 nike

我有一个函数“refreshDisplay”,它将帮助我创建动态元素。现在,我那里有一个小状况。在图像的“src”属性中,我将检查 obj.picture.thumbnail 是否以“/content”开头,然后添加“.jpg”作为“src”属性的扩展名,否则什么都不做!

请检查代码中类“.myLink”的图像。我该如何实现这一目标?

这是代码。

function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}

最佳答案

您可以将.attr(function)RegExp.protytpe.test()RegExp一起使用^\/content/ 匹配问题中描述的字符串,条件运算符连接 ".jpg" 或返回现有的 src 或空字符串。

.attr("src", function(i, src) {
return /^\/content/.test(obj.picture.thumbnail) ? src + ".jpg" : src
})

关于javascript - 如果动态元素通过条件,则更改其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43406135/

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