如何在单击时获取列表中的每个对象

时间:2016-06-25 14:19:11

标签: javascript jquery

我有问题清单。 我有一个html,f.e。,.每次点击,更改html" .title"从对象的下一个问题。 点击按钮,我得到:"做我好吗?", 接下来,我得到:"谁是最好的男人?"等等...



var questions = {
	first: "Is it good to be me?",
	second: "Who is the best man?",
	third: "Do you believe?",
	fourth: "Are you sexy?"
};
var txt = "";
var x;

for(x in questions) {
	txt += questions[x] + "<br>";
  console.log(txt)
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以使用array代替object

&#13;
&#13;
var questions = [
    "Is it good to be me?",
    "Who is the best man?",
    "Do you believe?",
    "Are you sexy?"
];

var index = 0;
$("button").click(function(){
    $("div").text(questions[index]);
    index++;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<br/>
<button>Get question</button>
&#13;
&#13;
&#13;

要获取问题索引,请使用index变量。您也可以使用data-index属性来执行此操作。

答案 1 :(得分:-1)

您可以尝试:

for(x in questions) {
    txt += questions[x] + "\n";
}
console.log(txt)