样式不正常

时间:2014-07-04 11:41:28

标签: javascript html css

我试图将第一个元素显示为不同的颜色。我能够做到这一点,但onalert,它显示数字和风格,而不仅仅是数字。我只想提醒1。我的代码是:

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            }
        return array;
    }

var myArray = ['1','2','3','4','5','6','7','8','9','10'];

newArray = myArray;

for (i=0;i<newArray.length;i++) {
    var p = document.createElement('p');
    var  color = "green";

    if((i == 0) || (i ==1) || (i == 2) || (i ==3)){
    p.innerHTML = "<p style='color:"+color+"'>"+newArray[i]+"</p>";
    }
    else{
        p.innerHTML = newArray[i];
    }
    p.onclick = showAlert; 
    document.body.appendChild(p);
}

         function showAlert() {
                  alert("onclick Event detected! " + this.innerHTML);
         }

此处fiddle。在点击1以外的元素时,它会显示已点击的数字,但点击1后会显示<p style="color:green">1</p>

5 个答案:

答案 0 :(得分:1)

将提醒更改为innerText

JSFiddle

答案 1 :(得分:0)

试试这个: -

alert("onclick Event detected! " + this.textContent);

答案 2 :(得分:0)

Updated Fiddle

更新Javascript

 function showAlert() {
          alert("onclick Event detected! " + this.textContent);
 }

More Detailed answer

答案 3 :(得分:0)

尝试使用innerText,因此你的showAlert-Function看起来像这样:

function showAlert() {
    alert("onclick Event detected! " + this.innerText);
}

答案 4 :(得分:0)

嘿而不是 innerHTML 使用 textContent

`function showAlert() 
{
    alert("onclick Event detected! " + this.textContent)
}`