我正在尝试在javascript不使用 的情况下创建一个按钮元素jQuery。
当我尝试将其附加到 DOM 时,我不断收到错误消息。
“无法读取 null 的属性‘appendChild’”
我到处都找遍了,但找不到如何创建按钮。在 w3Schools 示例中,他们在已经在 HTML 中创建的按钮元素上使用了一个函数,这不是我想要做的。这就是我所拥有的。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="myapp.js"></script>
</head>
<body>
<div id="btn">Button Here</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
myapp.js
var element = document.createElement("button");
element.appendChild(document.createTextNode("Click Me!"));
var page = document.getElementById("btn");
page.appendChild(element);
console.log(element);
Run Code Online (Sandbox Code Playgroud) 我正在尝试在 html 列表元素上使用 onclick 函数。函数显示被调用,但我没有得到值。它在控制台中显示未定义。代码:
function display() {
var x = document.getElementById('tags').selectedIndex;
console.log(x);
}Run Code Online (Sandbox Code Playgroud)
<ul id="tags">
<li id="android" value="android" onclick="display()">android</li>
<li id="swing" value="swing" onclick="display()">swing</li>
<li id="eclipse" value="eclipse" onclick="display()">eclipse</li>
<li id="spring" value="spring" onclick="display()">spring</li>
<li id="hibernate" value="hibernate" onclick="display()">hibernate</li>
<ul>Run Code Online (Sandbox Code Playgroud)
我有这个脚本给我Geo位置,比如"CA"或"US".我想在我的html基础上显示一个特定的用户位置.有什么建议?
HTML:
<div id="ip">Loading...</div>
<div id="country_code"></div>
<div id="country_code">Hello Canada</div>
<div id="country_code">Hello USA</div>
<script>
$.get("https://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
$("#country_code").html(response.country_code);
}, "jsonp");
document.getElementById("US").style.display = "block";
document.getElementById("CA").style.display = "block";
</script>
Run Code Online (Sandbox Code Playgroud)
CSS:
#US { text-align: left; color: blue; display:none;}
#CA { text-align: left; color: blue; display:none;}
Run Code Online (Sandbox Code Playgroud)