HTML/Javascript change div content

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

I have simple HTML code with some javascript, it looks like:

          

I just wanted to be able change div's content (it's inner html) with selecting one of "A" or "B" radio buttons, but div#content does not have javascript attribute "value", so I am asking how it can be done.

回答1:

Assuming you're not using jQuery or some other library that makes this sort of thing easier for you, you can just use the element's innerHTML property.

document.getElementById("content").innerHTML = "whatever"; 


回答2:

$('#content').html('whatever'); 


回答3:

Get the id of the div whose content you want to change then assign the text as below:

  var myDiv = document.getElementById("divId");   myDiv.innerHTML = "Content To Show"; 


回答4:

     JS Bin

-----------------JS- code------------

var targetDiv = document.getElementById('content');     var htmlContent = '';      function populateData(event){       switch(event.target.value){         case 'A':{          htmlContent = 'Content for A';           break;         }         case 'B':{           htmlContent = "content for B"; break;         }       }       targetDiv.innerHTML = htmlContent;     } 

Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);  Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text. 

Live Code

https://jsbin.com/poreway/edit?html,js,output



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!