试图让这个字符串出现在一个段落中

时间:2017-11-07 20:59:31

标签: javascript html

尝试将我在JavaScript中的字符串显示在HTML页面的一个段落中,将鼠标悬停在另一个段落上。

function showInfo()
{
    for (i = 0; i < object2; i = i + 1)
    {
        var myParagraph = "Name of Business: " + info.insurance[i].name + "\nState: " + info.insurance[i].state + "\nDiscount: " + info.insurance[i].discount + "\n" + "(" + i + 1 + "of" + object2 + ")"
    }
}

myDiscount.addEventListener("mouseover", showInfo, false);

myDiscount.addEventListener("mouseout", showInfo, false);
<p id="discount">Show me the discounts!</p>

<p id="myP"></p>

1 个答案:

答案 0 :(得分:0)

如果您希望每次将鼠标悬停在段落上时显示info.insurance数组的下一个元素,则不应使用for循环。这将一次完成,而不是每次鼠标悬停。您需要将计数器放在一个全局变量中,并在每次调用函数时将其递增。

Yuo通过将其分配给段落的innerHTML来显示它。您还需要使用<br>而不是\n来创建换行符(除非段落的样式为pre)。

var insurance_counter = 0;
function showInfo() {
    var myParagraph = "Name of Business: " + info.insurance[insurance_counter].name + "<br>State: " + info.insurance[insurance_counter].state + "<br>Discount: " + info.insurance[insurance_counter].discount + "<br>(" + (insurance_counter + 1) + "of" + object2 + ")";
    document.getElementById("myP").innerHTML = myParagraph;
    insurance_counter++;
    if (insurance_counter >= object2) { // wrap around when limit reached
        insurance_counter = 0;
    }
}