我正在尝试在选中单选按钮时更新HTML5占位符属性。我没有使用JQuery,所以更喜欢内联JavaScript解决方案。我知道我错过了一些简单的事情,但我正在努力教自己!
<script type="text/javascript">
function ModifyPlaceHolder1 () {
var input = document.getElementById ("MyQuery");
input.placeholder = "Search books e.g. Harry Potter";
}
function ModifyPlaceHolder2 () {
var input = document.getElementById ("MyQuery");
input.placeholder = "Search journals e.g. New Scientist";
}
</script>
<input type="text" id="MyQuery" placeholder="Search resources" name="q" />
<input type="radio" value="" id="All" name="s.cmd" checked="checked" />
<label for="All">All</label>
<input type="radio" onclick="ModifyPlaceHolder1 ()" value="" id="Books" name="s.cmd" checked="checked" />
<label for="Books">Books</label>
<input type="radio" onclick="ModifyPlaceHolder2 ()" value="" id="Journals" name="s.cmd" checked="checked" />
<label for="Journals">Journals</label>
答案 0 :(得分:2)
这是一种没有任何内联JS的方法。一点点清洁,更容易跟踪(IMO)。
<input type="text" id="MyQuery" placeholder="Search resources" name="q" />
<input type="radio" value="" id="All" name="s.cmd" checked="checked" />
<label for="All">All</label>
<input type="radio" value="" id="Books" name="s.cmd" checked="checked" />
<label for="Books">Books</label>
<input type="radio" value="" id="Journals" name="s.cmd" checked="checked" />
<label for="Journals">Journals</label>
var books = document.getElementById("Books");
var journals = document.getElementById("Journals");
var input = document.getElementById("MyQuery");
books.onclick = function() {
input.placeholder = "Search books e.g. Harry Potter";
}
journals.onclick = function() {
input.placeholder = "Search journals e.g. New Scientist";
}
答案 1 :(得分:0)
我会使用以下单个函数对其进行编程:
<script>
function ModifyPlaceHolder(element) {
var data = {
All: 'Search resources',
Books: 'Search books e.g. Harry Potter',
Journals: 'Search journals e.g. New Scientist'
};
var input = element.form.MyQuery;
input.placeholder = data[element.id];
}
</script>
<form>
<input type="text" id="MyQuery" placeholder="Search resources" name="q">
<label for="All"><input type="radio" onclick="ModifyPlaceHolder(this)" id="All" name="s.cmd" checked> All</label>
<label for="Books"><input type="radio" onclick="ModifyPlaceHolder(this)" id="Books" name="s.cmd"> Books</label>
<label for="Journals"><input type="radio" onclick="ModifyPlaceHolder(this)" id="Journals" name="s.cmd"> Journals</label>
</form>
请注意:
当您看到一个包含在一个元素中的相同侦听器的字符串时,您可以查看在父元素上放置一个侦听器。搜索“事件委托”。
答案 2 :(得分:-1)
试试这个:
<script>
function ModifyPlaceHolder(element) {
var data = {
All: 'Search resources',
Books: 'Search books e.g. Harry Potter',
Journals: 'Search journals e.g. New Scientist'
};
var input = document.getElementById("MyQuery");
input.placeholder = data[element.id];
}
</script>