我的javascript文件中有一个问题列表。每个问题都有一个问题编号和问题描述和选项。可以在问题列表的任何位置添加问题。因此,如果在所有问题的顶部添加一个问题,那么我需要更改以下所有问题的问题编号。怎么能实现这一点。我可以使用javascript吗?
答案 0 :(得分:1)
我建议对每个问题使用<ol>
,然后让页面处理回复数字。
否则你需要在插入之前设置一个目标数字,并且对于列表中的每个元素,你将检查它的数量是否大于目标,然后如果这样增加数字。
var Target = //new number that I want the inserted question to be
foreach (element in list) {
if (element.Number > Target) element.Number += 1;
}
list.add( //new question with # set to Target );
答案 1 :(得分:1)
这很有效。
<ol id="questions_list"></ol>
var questions = ["A foo walks into a bar. What happens?", "Why did foo cross the road?"];
addQuestion("foo", 1);
function addQuestion(question, position)
{
if(position > 0 && position < questions.length)
{
var firstHalf = questions.slice(0, position);
var secondHalf = questions.slice(position, questions.length);
firstHalf.push(question);
questions = firstHalf.concat(secondHalf);
console.log("slice");
}else if(position <= 0)
{
questions.unshift(question);
console.log("beginning");
}else if(position >= questions.length)
{
questions.push(question);
console.log("end");
}
updateQuestionList();
}
function updateQuestionList()
{
var questions_list = document.getElementById("questions_list");
questions_list.innerHTML = "";
for(var i=0;i<questions.length;i++)
{
var question = document.createElement("LI");
question.innerHTML = questions[i];
questions_list.appendChild(question);
}
}
答案 2 :(得分:0)
你可以使用有序列表(ol)和jQuery做这样的事情:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type ="text/javascript">
$(function(){
var n = 2;
$('button').delegate('click', function(){
$(this).parents('li').after('<li><p><span>Question'+n+'</span><button>Create new question</button></p></li>');
n += 1;
})
})
</script>
</head>
<body>
<ol>
<li>
<p><span>Question 1</span><button>Create new question</button></p>
</li>
</ol>
</body>
</html>
答案 3 :(得分:0)
数组原型(有趣!=)):
// zero-based insert
Array.prototype.insert = function(index, item) {
var i = 0, list = [];
if (this.length == index) {
list = this;
list.push(item);
return list;
}
for(; i < this.length; i++) {
if (index == list.length) {
list.push(item);
i--;
} else {
list.push(this[i]);
}
}
return list;
};
Array.prototype.print = function (base) {
base = base || 1;
for (var i = 0, out = []; i < this.length; i++) {
out.push((base + i) + '. ' + this[i]);
}
return out.join("\n");
};
list = ['when?', 'where?', 'why?'];
list = list.insert(0, 'who?'); // first: ["who?", "when?", "where?", "why?"]
list = list.insert(3, 'how?'); // 4th: ["who?", "when?", "where?", "how?", "why?"]
list = list.insert(list.length, 'last?'); // last: ["who?", "when?", "where?", "how?", "why?", "last?"];
list.print();
/**
"1. who?
2. when?
3. where?
4. how?
5. why?
6. last?"
**/