如何将 jQuery 信息添加到 html 表单中



这个html表单由一些javascript代码显示。现在,我想在单击表格中的单元格时将它们的信息添加到此类警报中。

我该怎么做?

<div class='alertBox' id='box'>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#tableBody td').on('click', function() {
            alert($(this).html() + ' ' + months[currentMonth] + ' ' + currentYear);
        });
    });
    </script>
    <form>
        <input name='Event' type='text' value='Event'> <br>
    </form>
    <a onclick='unpop()' class='close'>Close</a>
</div>
...

这是一个网站,您可以在其中将约会添加到日历中,然后约会将由树莓派显示。

谢谢你的回答。我已经找到了另一种解决方案。如果您有兴趣,这里是:

$(document).ready(function() {
    $('#tableBody td').on('click', function() {
        var cellIndex = document.getElementById('displayDate').innerHTML = $(this).text() + ' ' + months[currentMonth] + ' ' + currentYear;
    });
});
function pop() {
    document.getElementById('box').style.display = 'block';
    cellIndex;
}
function unpop() {
    document.getElementById('box').style.display = 'none';
}

如果警告框的 HTML 是由 javascript 添加的,那么您需要使用 .on() 来捕获用户事件(这称为事件委托(。此外,当你这样做时,你必须将.on()方法附加到一个在javascript运行之前肯定存在的元素 - $(document)始终是安全的。

试试这个:

$(document).ready(function() {
  $(document).on('click', '#tableBody td', function() {
    let txt = $(this).text();
    $('#box input[name=Event]').val(txt);
    $('#box').show();
  });
  
  $(document).on('click', '#box a.close', function(){
    $('#box').hide();
  });
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
#box{position:absolute;top:5vh;left:20vw;padding:2vh;background:wheat;display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class='alertBox' id='box'>
  <form>
    <input name='Event' type='text' value='Event'> <br>
  </form>
  <a class='close'>Close</a>
</div>
<table>
  <thead><th>Name</th><th>Vehicle</th></thead>
  <tbody id="tableBody">
    <tr><td>Bob</td><td>Car</td></tr>
    <tr><td>Sam</td><td>Truck</td></tr>
    <tr><td>Fred</td><td>Bike</td></tr>
  </tbody></table>

最新更新