Как изменить значение src на несколько < img > теги, использующие «для цикла»?

$("tr:has(div:contains('-'))").hide(); будет искать - (отрицательный) в каждом DIV TD, а затем это решение не будет работать, если в будущем какой-либо div поступит в TD.

В нижеприведенном решении он будет искать отрицательное значение только в negMoney, который является вторым TD строки.

$(".negMoney").each(function(i){
   var val = $(this).html();
   var isNegative = Number((val.substr(1)).replace(/\,/g,'')) < 0;       
   if(isNegative) { 
      $("tr:eq( "+ i +" )").hide(); 
   }
});
0
задан PGCodeRider 18 January 2019 в 23:59
поделиться

2 ответа

В вашем коде есть ряд проблем:

button.onclick = display(imgs)

button.onclick следует установить для самой функции, а не для ее значения. об этом, когда он работает на заданном значении. Вместо этого вы можете использовать .bind .

for (let i = 0; i > arr.length; i++){

i начинается с 0, что означает, что оно всегда будет ниже arr.length, и поэтому этот цикл никогда не будет выполняться. [1127 ]

i.src = ...

i - это переменная, содержащая число, а не изображение с индексом i. Вы, вероятно, хотите использовать здесь imgs[i], который ссылается на изображение №. i.


Это один из способов применения предложенных выше исправлений:

const dice1 = document.getElementById('dice1');
const dice2 = document.getElementById('dice2');
const dice3 = document.getElementById('dice3');
const dice4 = document.getElementById('dice4');
const dice5 = document.getElementById('dice5');
const dice6 = document.getElementById('dice6');
const button = document.getElementById('button');

const imgs = [dice1, dice2, dice3, dice4, dice5, dice6];

let pics = ['https://i.postimg.cc/MfVDpSmQ/Eagle.jpg', 
    'https://i.postimg.cc/QKGQPzZx/Man.jpg', 
    'https://i.postimg.cc/1g7MWMzf/Dog.jpg', 
    'https://i.postimg.cc/xc9HzM07/Telephone.jpg', 
    'https://i.postimg.cc/4mwcbyy3/Robot.jpg', 
    'https://i.postimg.cc/ctRRNcd7/Moon.jpg', 
    'https://i.postimg.cc/xJW5QCMQ/Dinosaur.jpg',
    'https://i.postimg.cc/hhdMrLRt/Fish.jpg', 
    'https://i.postimg.cc/Ty1JWmcG/Flowers.jpg'];


const display = () => {
    for (let i = 0; i < imgs.length; i++) {
        imgs[i].src = pics[Math.floor(Math.random() * pics.length)]
    }
};

button.onclick = display;
<button id="button">Roll the dice</button>
<img id="dice1"/>
<img id="dice2"/>
<img id="dice3"/>
<img id="dice4"/>
<img id="dice5"/>
<img id="dice6"/>


Редактировать: чтобы избежать повторения одного и того же изображения, используйте .splice после вычисления случайного индекса изображения (как предложено @CertainPerformance):

[ 112]
<button id="button">Roll the dice</button>
<img id="dice1"/>
<img id="dice2"/>
<img id="dice3"/>
<img id="dice4"/>
<img id="dice5"/>
<img id="dice6"/>

0
ответ дан Itai Steinherz 18 January 2019 в 23:59
поделиться

Индексированные id значения в документе обычно являются плохой идеей; рассмотреть возможность использования классов вместо. Кроме того, вместо цикла for (который требует ручной итерации и не имеет абстракции), рассмотрите возможность использования вместо forEach:

const dice = document.querySelectorAll('.dice');
button.onclick = () => {
  dice.forEach((die) => {
    die.src = pics[Math.floor(Math.random() * pics.length)]
  });
};

const dice = document.querySelectorAll('.dice');
const pics = ['https://i.postimg.cc/MfVDpSmQ/Eagle.jpg',
  'https://i.postimg.cc/QKGQPzZx/Man.jpg',
  'https://i.postimg.cc/1g7MWMzf/Dog.jpg',
  'https://i.postimg.cc/xc9HzM07/Telephone.jpg',
  'https://i.postimg.cc/4mwcbyy3/Robot.jpg',
  'https://i.postimg.cc/ctRRNcd7/Moon.jpg',
  'https://i.postimg.cc/xJW5QCMQ/Dinosaur.jpg',
  'https://i.postimg.cc/hhdMrLRt/Fish.jpg',
  'https://i.postimg.cc/Ty1JWmcG/Flowers.jpg'
];
const button = document.querySelector('#button');
button.onclick = () => {
  dice.forEach((die) => {
    die.src = pics[Math.floor(Math.random() * pics.length)]
  });
};
[ 112]

Чтобы гарантировать, что изображения не повторяются, каждый раз, когда нажимается кнопка, сделайте копию массива, затем splice выделите выбранный элемент:

[113 ]

const dice = document.querySelectorAll('.dice');
const pics = ['https://i.postimg.cc/MfVDpSmQ/Eagle.jpg',
  'https://i.postimg.cc/QKGQPzZx/Man.jpg',
  'https://i.postimg.cc/1g7MWMzf/Dog.jpg',
  'https://i.postimg.cc/xc9HzM07/Telephone.jpg',
  'https://i.postimg.cc/4mwcbyy3/Robot.jpg',
  'https://i.postimg.cc/ctRRNcd7/Moon.jpg',
  'https://i.postimg.cc/xJW5QCMQ/Dinosaur.jpg',
  'https://i.postimg.cc/hhdMrLRt/Fish.jpg',
  'https://i.postimg.cc/Ty1JWmcG/Flowers.jpg'
];
const button = document.querySelector('#button');
button.onclick = () => {
  const picsCopy = pics.slice();
  dice.forEach((die) => {
    const [src] = picsCopy.splice(Math.floor(Math.random() * picsCopy.length), 1);
    die.src = src;
  });
};
<img class="dice">
<img class="dice">
<img class="dice">
<img class="dice">
<img class="dice">
<img class="dice">
<button id="button">Roll the dice</button>

0
ответ дан CertainPerformance 18 January 2019 в 23:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: