我有简单的HTML代码和一些javascript,它看起来像:
<html>
<head>
<script type="text/javascript">
function changeDivContent() { // ...
};
</script>
</head>
<body>
<input type="radio" name="radiobutton" value="A" onClick="changeDivContent()">
<input type="radio" name="radiobutton" value="B" onClick="changeDivContent()">
<div id="content"></div>
</body>
</html>
我只是想通过选择“A”或“B”单选按钮之一来改变div的内容(它的内部html),但是div#content没有javascript属性“value”,所以我问怎么做。
答案 0 :(得分:346)
假设你没有使用jQuery或其他一些让你更容易理解这类事情的库,你可以使用元素的innerHTML属性。
document.getElementById("content").innerHTML = "whatever";
答案 1 :(得分:18)
$('#content').html('whatever');
答案 2 :(得分:9)
获取要更改其内容的div
的ID,然后分配如下文字:
var myDiv = document.getElementById("divId");
myDiv.innerHTML = "Content To Show";
答案 3 :(得分:6)
您可以使用以下帮助器功能:
function content(divSelector, value) {
document.querySelector(divSelector).innerHTML = value;
}
content('#content',"whatever");
#content
必须有效的CSS selector
这里是working example。
另外-今天(2018.07.01)我对jquery和纯js解决方案进行了速度比较(Chrome 67.0.3396.99(64位)上的MacOs High Sierra 10.13.3,Safari 11.0.3(13604.5.6),Firefox 59.0.2(64位)):
document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever'); // jQuery
jquery解决方案比纯js解决方案慢:在firefox上为69%,在Safari中为61%,在chrome上为56%。纯js最快的浏览器是firefox,每秒可进行560M次操作,第二次是safari 426M,最慢的是chrome 122M。
所以优胜者是纯js和firefox (比chrome快3倍!)
您可以在计算机上对其进行测试:https://jsperf.com/js-jquery-html-content-change
答案 4 :(得分:1)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
<input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">
<div id="content"></div>
</body>
</html>
----------------- 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.
直播代码
答案 5 :(得分:0)
将onClick更改为onClick="changeDivContent(this)"
,然后尝试
function changeDivContent(btn) {
content.innerHTML = btn.value
}
function changeDivContent(btn) {
content.innerHTML = btn.value
}
<input type="radio" name="radiobutton" value="A" onClick="changeDivContent(this)">
<input type="radio" name="radiobutton" value="B" onClick="changeDivContent(this)">
<div id="content"></div>