样式不能正常工作

Styling not working properly

本文关键字:工作 常工作 不能 样式      更新时间:2023-09-26

我试图将第一个元素显示为不同的颜色。我可以这样做,但是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);
         }

这是小提琴。点击1以外的元素,显示点击的数字,但点击1,显示的是<p style="color:green">1</p>

更改innerText的警告

JSFiddle

试试这个:-

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

更新小提琴

更新Javascript

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

更详细的答案

try innerText,所以你的showAlert-Function看起来像这样:

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

他们用textContent 代替innerHTML

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