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

Change the attribute of a dynamic element if it passes the condition

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

请检查代码中带有 class '.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" 或 return 现有 src 或空字符串。

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

替换

$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),

$('<img>')
    .addClass('myLink')
    .attr('src', 
        obj.picture.thumbnail +
        ( obj.picture.thumbnail.indexOf( '/content' ) === 0 ? '.jpg' : '' ) ), 
$('<br>'),