javascript - 在按钮上单击显示特定元素

标签 javascript jquery html

我面临的情况是向用户呈现许多不同的按钮。

当单击任何按钮时,都会生成一个不同的表单,并在 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/

相关文章:

javascript - 如何让已取消的警报在警报 "cancel"之后返回到相同的先前选项?

jquery - 为什么单击事件后聚焦时不应用浏览器默认聚焦样式?

javascript - 折叠/展开所有菜单项。 - HTML/JS/CSS/ Bootstrap 3

html - 设置一个div宽度,对齐div中心和文本左对齐

javascript - 使用 LocalFileSystem 存储和显示图像

javascript - 如何在图像上方设置指标

javascript - 尝试使用 javascript 和媒体查询更改边距

javascript - 如何从特定语言的下拉列表中删除 "powered by google translate"并通过谷歌翻译器翻译网页

javascript - 三元表达式 JavaScript 中的三元表达式

jquery - 单击后退按钮以提供页面结果空白页