在循环

时间:2017-12-29 18:20:10

标签: javascript php html

我正在从数据库中循环我的帖子,我正在尝试根据值更改投票的颜色。如果0 =黑色,则< 0 =红色,> 0 =绿色。我的第一个尝试是在h1标签上为投票值设置一个id,并从那个方向修改颜色。它适用于第一篇文章,但所有其他帖子都没有受到影响。有没有人知道我该怎么做?

PHP& HTML:

while ($row = $stmt->fetch()) {
echo '<h1 id="scoreCounter">'.$row['votes'].'</h1>';
}

使用Javascript:

var score = document.getElementByid("scoreCounter");
var scoreValue = 10;
checkScore();



function checkScore() {
if (scoreValue < 0) {
  score.style.color = "#FF586C";
} else if (scoreValue > 0) {
  score.style.color = "#6CC576";
} else {
  score.style.color = "#666666";
}
}

3 个答案:

答案 0 :(得分:6)

一种方法是在标题中添加一个类,具体取决于要设置的颜色。

并为此

定义css样式
def to_representation(self, instance):
    ret = super(BlastEventSerializer, self).to_representation(instance)

    instrument_id = self.context['request'].query_params.get('instrument_id')
    if instrument_id:
        ret['size'] = 77  # some custom calculations
    return ret

答案 1 :(得分:0)

id在HTML中应该是唯一的。请改用classgetElementsByClassName

答案 2 :(得分:0)

您永远不应该使用相同的ID创建多个元素。

以下是一大块代码,它找到类名为'score-counter'的所有元素,然后枚举所有元素,并根据score属性中的值更改文本颜色。

&#13;
&#13;
var scoreEls = document.querySelectorAll(".score-counter");
if (scoreEls.length>0) {
  scoreEls.forEach(checkScore);
}

function checkScore(el) {
  var scoreValue = Number(el.getAttribute('score'));
  if (scoreValue < 0) {
    el.style.color = "#FF586C";
  }
  else if (scoreValue > 0) {
    el.style.color = "#6CC576";
  }
  else {
    el.style.color = "#666666";
  }
}
&#13;
<div>Title 1: <span class="score-counter" score="30">30</span></div>
<div>Title 2: <span class="score-counter" score="0">0</span></div>
<div>Title 3: <span class="score-counter" score="-5">-5</span></div>
<div>Title 4: <span class="score-counter" score="12">12</span></div>
<div>Title 5: <span class="score-counter" score="-53">-53</span></div>
<div>Title 4: <span class="score-counter" score="0">0</span></div>
&#13;
&#13;
&#13;

你的PHP需要是这样的:

while ($row = $stmt->fetch()) {
  echo '<div>Title 4: <span class="score-counter" score="'.$row['votes'].'">'.$row['votes'].'</span></div>';
}