我面临的情况是向用户呈现许多不同的按钮。
当单击任何按钮时,都会生成一个不同的表单,并在 dom 中注入(inject)一个字符串,以通知用户按下了哪个表单。
伪代码:
<div id="notifier">
<h1 class="text-center">
<> SOMETHING SHOULD GO HERE<>
<script>
$(document).ready(function(){
$("#notifier").hide(); //hide the initial string since no form is pressed at the beginning
$("#editForm1").hide(); //hides form1 since no button is pressed
$("#editForm2").hide(); //hides form2 since no button is pressed
$("#btn_1").click(function(e) {
//SOMETHING SHOULD GO HERE AS WELL
$("#editForm1").show();
当按下button1时,form1会在dom中生成。
但我还想用 id="notifier"
在 div 中注入(inject)字符串“Form1”,让用户知道生成了哪个表单。
我该怎么做?
最佳答案
- 使用
data-*
属性存储目标选择器:data-formshow="#form-1"
- 使用 CSS 类来隐藏表单:
.none { display: none; }
- 使用 jQuery 选择按钮和表单
- 使用 jQuery
.addClass()
和.removeClass()
操作.none
类 - 使用
.not()
从集合中排除特定元素:
jQuery($ => {
const $notifier = $('#notifier'); // the <H1>
const $buttons = $('[data-showform]'); // the <button>s
const $forms = $('[id^="form-"]'); // the <form>s
$buttons.on('click', function(ev) {
ev.preventDefault();
const sel = $(this).data('showform'); // Get the selector
const txt = $(this).text(); // Get the text
const $form = $(sel); // Get the form Element
$forms.not($form).addClass('hide'); // Hide other forms
$form.removeClass('hide'); // Show target form
$notifier.text( txt ); // Preview button text into H1
});
});
.hide { display: none; }
<h1 id="notifier">CLICK A BUTTON</h1>
<button type="button" data-showform="#form-1">FORM ONE</button>
<button type="button" data-showform="#form-2">FORM TWO</button>
<form id="form-1" class="hide">I'm form ONE</form>
<form id="form-2" class="hide">I'm form TWO</form>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
关于javascript - 在按钮上单击显示特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58175332/