我有这段代码,在单击按钮时显示一个标签,但我需要以下内容:
null
(function() {
$('button').on('click', function() {
$("#action").html("button was clicked");
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button>Action</button>
<label id="action"></label>
null
参见示例:https://jsfiddle.net/fr4x32g7/
null
(function() {
var active="";
$('button').on('click', function(e) {
var id = "#" +e.target.value;
$(active).html("");
active=id;
$(id).html("button was clicked");
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button value="action">Action</button>
<label id="action"></label>
<button value="action1">Action</button>
<label id="action1"></label>
这样解决问题了吗?
null
(function() {
$('#button1').on('click', function() {
$("#action").html("button1 was clicked");
});
$('#button2').on('click', function() {
$("#action").html("button2 was clicked");
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button id="button1">Action1</button>
<button id="button2">Action2</button>
<label id="action"></label>
我假设这两个标签最初都是隐藏的,如果用户点击按钮,只显示其中一个。 下面是一个解决方案:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button data-label="action1">Action 1</button>
<button data-label="action2">Action 2</button>
<br>
<label class="action" id="action1" style="display:none;">button 1 was clicked</label>
<label class="action" id="action2" style="display:none;">button 2 was clicked</label>
和
$(function() {
$('button').on('click', function() {
$("#" + $(this).data('label')).show().siblings("label").hide();
});
});
fiddle:https://jsfiddle.net/0phz62OT/
基本上,我们通过一个属性来绑定按钮和它的标签,每当单击按钮时,绑定到它的标签就会显示出来,而同级标签就会隐藏起来。