简体   繁体   English

如何在按钮单击时刷新 div 内容

[英]How do I refresh div contents on button click

I have a script inside a div which I want to refresh when someone clicks a button with a unique ID.我在 div 中有一个脚本,当有人单击具有唯一 ID 的按钮时,我想刷新该脚本。

I have some data which will be displayed inside the div - which I need to refresh without refreshing the whole page.我有一些数据将显示在 div 内 - 我需要刷新而不刷新整个页面。

I've found a solution which changes a border colour but I can't quite simplify it to what I need.我找到了一个改变边框颜色的解决方案,但我不能将它简化为我需要的。 Here's what I have so far这是我到目前为止所拥有的

 var storeColor = 'red'; $('#container').on('click', 'button', function() { var $p = $('#content p'); var tmp = $p.css('border-color'); $p.css('border-color', storeColor); storeColor = tmp; });
 </div> <button type="button">Refresh DIV</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="container"> Contents of div </div>

I think there are a few problems with your code... The button is outside of the container and thats the reason the click listener doesn't work.我认为您的代码存在一些问题...该按钮位于容器之外,这就是单击侦听器不起作用的原因。 Inside the click function you try to access a paragraph p inside some element with the id content which doesn't exist in your code在单击 function 内,您尝试访问某个元素内的段落p ,其中的 id content在您的代码中不存在

 var storeColor = 'red'; $('#btnRefresh').on('click', function() { var $p = $('#container'); $p.css('background-color', 'red'); $p.html('hello world'); });
 <button type="button" id="btnRefresh">Refresh DIV</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="container"> Contents of div </div>

Why not try changing the entire inner content of the div dynamically using document.querySelector('.div').innerHTML = html string为什么不尝试使用 document.querySelector('.div').innerHTML = html string动态更改 div 的整个内部内容

The above will not refresh the page if used upon a button click.如果在单击按钮时使用上述内容,则不会刷新页面。 You may want to use the preventDefault in the button's event listener too.您可能还想在按钮的事件侦听器中使用 preventDefault。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM