在jQuery Mobile中通过ID从数组中填充按钮值

Filling the button value from an array through the ID in jQuery Mobile

本文关键字:填充 数组 按钮 jQuery Mobile ID      更新时间:2023-09-26

我已经开始创建一个测验。今天所有的问题和答案都在同一个数组中。通过id的b1 - b4和函数getElementById,它成功地使用了HTMl, JavaScript和CSS。

但现在我想"转换"这个脚本在移动版本。所以我开始使用jQuery Mobile。我将getElementById更改为$("#variable").val(array);。然后用Firebug检查了一下。Firebug告诉我,按钮的值是用数组值填充的,但我不能在正常视图中看到它。

谁能告诉我解决我的错误的方法?

HTML-Buttons

                <input id='b1' type="button" value="" ONCLICK="analyseB1()"/>
                <input id='b2' type="button" value=""  ONCLICK="analyseB2()"/>

                <input id='b3' type="button" value=""  ONCLICK="analyseB3()"/>
                <input id='b4' type="button" value=""  ONCLICK="analyseB4()"/>
                <input id='next' type="button" value="Next Question" ONCLICK="next()"/>

JS-Function

function next()
{   
    document.getElementById('header').innerHTML = array[questioncounter][0];
    $("#b1").val(array[questioncounter][1]);
    $("#b2").val(array[questioncounter][2]);
    $("#b3").val(array[questioncounter][3]);
    $("#b4").val(array[questioncounter][4]);
    document.getElementById('next').style.display='none';
    document.getElementById('b1').style.backgroundColor = '';
    document.getElementById('b2').style.backgroundColor = '';
    document.getElementById('b3').style.backgroundColor = '';
    document.getElementById('b4').style.backgroundColor = ''; 

}

我的第一个建议是学习一些jQuery编程,你会发现它是基本的。现在,关于你的问题:

  • 使用<a href="#" id="b1" data-role="button"></a>创建按钮
  • 不使用onclick处理程序
  • 使用一个智能的jQuery选择器来避免重复的函数

:

<div data-role="page" id="page">
    <a href="#" id="b1" data-role="button"></a>
    <a href="#" id="b2" data-role="button"></a>
    <a href="#" id="b3" data-role="button"></a>
    <a href="#" id="b4" data-role="button"></a>
    <a href="#" id="next" data-role="button">Next question</a>
</div>
JavaScript

:

$(document).on("click", "[id^=b]", function(event, ui)
{
   alert(this.id);
});
$(document).on("click", "#next", function(event, ui)
{
   $("#b1").prop("innerHTML", "b1 button");
   $("#b2").prop("innerHTML", "b2 button");
   $("#b3").prop("innerHTML", "b3 button");
   $("#b4").prop("innerHTML", "b4 button");
   $("#next").css("display", "none");
   $("[id^=b]").css("backgroundColor", "");
});

JSFiddle