首页 > 解决方案 > 无法在 jquery 中打印从 Modal 中选择的值

问题描述

我创建了一个应用程序,我必须从模式中选择数据并在段落中打印结果。

下面的链接将有助于理解功能

https://jsfiddle.net/2empvtas/3/

模态被加载并打印结果,但两个值都被打印而不是选定的值。b

代码

   <p> Result will apper here
<span class='add-tax'></span>
</p>
<button class='w3-btn w3-ripple w3-blue-grey w3-round' onclick='document.getElementById("tax").style.display="block"' href=''>Add data rate</button>


<div id="tax" class='w3-modal w3-small w3-round' id='tax_modal'>
    <div class='w3-modal-content w3-animate-top w3-card-4 w3-round' style='width:50%'>
      <header class='w3-container w3-blue-grey'> 
        <span onclick="document.getElementById('tax').style.display='none'"
        class='w3-button w3-display-topright'>&times;</span><br>
        <h5>Action Required</h5>
      </header>
      <div class='w3-container'>
        <h5>Data List</h5>
 <table class="w3-table w3-responsible">
            <tr>
              <th>Name</th>
              <th>Amount</th>
            </tr>
            <tr>
              <th>abc</th>
              <td class='tax'>
                <p class='add_tax'>
                  1
                </p>
              </td>
            </tr>
            <tr>
              <th>efg</th>
              <td class='tax'>
                <p class='add_tax'>
                  2
                </p>
              </td>
            </tr>
          </table>
           </div>
       <footer class='w3-container w3-blue-grey'> 
        <br>
       <button onclick='document.getElementById("tax").style.display="none"' class='w3-round w3-button w3-blue w3-hover-pale-blue'>Cancel</button>
        <a style='text-decoration:none;' class='w3-round w3-button w3-red w3-hover-pale-red' href='#'>Delete</a>
        <br><br>
      </footer>
    </div>
  </div>

jQuery代码

$(".add_tax").click(function(){
    //console.log("done done");
    //var tax;var result;
    $('.add_tax').each(function(){
        tax = $('.add_tax').text();
        $('.add-tax').text(tax); 
       console.log("1"+tax);
       document.getElementById('tax').style.display = 'none';
    });
    //$('.add-tax').text(tax); 
   //$("#tax_modal").remove();

    /*
    var tax = $('.add_tax').text();
        console.log(tax);
    $('.add-tax').text($('.add_tax').val()); 
    $("#tax_modal").hide();*/
});

标签: jqueryhtml

解决方案


您需要像这样更改您的 jquery 代码:

$(".add_tax").click(function(){
    tax = $(this).text();
    $('.add-tax').text(tax);
    document.getElementById('tax').style.display = 'none';
});

请注意,我已删除.each功能。因为.each将遍历所有.add_tax类并获取其文本。这是我们不想要的。


推荐阅读