简体   繁体   English

如何刷新单个div的内容

[英]How do I refresh the contents of a single div

I'm implementing a simple web-page, in that page, I have multiple div objects, what I'm trying to do is refresh the contents of a single div based on the user clicking a button or entering text in an input field. 我正在实现一个简单的网页,在该页面中,我有多个div对象,我想要做的是基于用户单击按钮或在输入字段中输入文本来刷新单个div的内容。

So far I've found solutions online that apply to php which I know nothing about to be honest, can somebody provide me with a solution using javascript or jquery and simple html? 到目前为止,我已经找到了适用于php的在线解决方案,但我实在不了解,有人可以使用javascript或jquery和简单的html为我提供解决方案吗?

The simplest route if you're new to all of this is to change the html of the div. 如果您不熟悉所有这些,最简单的方法是更改​​div的html。 Given a div with id "ponies", you can change its contents via: 给定一个ID为“ ponies”的div,您可以通过以下方式更改其内容:

document.getElementById("ponies").innerHTML = '<p>new html block</p>'

If you want to swap out a div contents for another, you can opt instead to alter the DOM tree by a createChild after the div, and then removing the div. 如果要将div内容换成另一个,则可以选择在div之后由createChild更改DOM树,然后删除div。 The innerHTML approach, while simple to understand, is a bit of a blunt (and slow) tool, compared to modifying the DOM itself. 与修改DOM本身相比, innerHTML方法虽然简单易懂, innerHTML有点钝(且缓慢)。 But if you're doing it rarely, and the html is simple, who cares? 但是,如果您很少这样做,并且html很简单,谁在乎呢?

If you have a form input for a forename then you can do: 如果您有一个用于输入姓名的表单,则可以执行以下操作:

function showForename(forenameDiv) {
    var text = "<p>Your forename is " + document.getElementById(forenameDiv).text + "</p>";
    document.getElementById("ponies").innerHTML = text; 
}

And put the call in the button's onClick event: 并将呼叫放入按钮的onClick事件中:

<input type="button" value="Who am I?" onclick="showForename('forenameinput')" />

Where forenameinput is the id of the forename form input. 其中forenameinput是姓氏形式输入的id。 To learn more about all this stuff, look at the w3schools website . 要了解有关所有这些东西的更多信息,请访问w3schools网站

an example with jquery: jQuery的示例:

$("input.button").click(function(){
   $('div#content').load('ajax/test.php', function() {
      console.log('loaded.');
   });
});

Based on @PhilH s answer here a cleaner jQuery solution: 根据@PhilH的答案,这里提供了一种更清洁的jQuery解决方案:

jQuery( '#yourInput' ).click( function(){
    jQuery( '#ponies' ).text( 'You wrote: ' + this.value );
} );

Even in jQuery you can type in pure HTML if you want: 即使在jQuery中,您也可以输入纯HTML:

jQuery( '#yourInput' ).click( function(){
    jQuery( '#ponies' ).html( '<span>You wrote: <b>' + this.value + '</b></span>' );
} );

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

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