如何在输入标签中传递值?

时间:2019-05-26 13:33:51

标签: javascript

通常,我尝试在p,div和pre标签中传递值,并且现在在上面的标签中显示值,而我在输入标签中传递国家/地区名称。但值不会显示在输入标签中。这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>

<script> 

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.country_name + ", " + response.region);
    $("#country_name").html(response.country_name);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");

</script>

</body>
</html>

谢谢。

3 个答案:

答案 0 :(得分:2)

只有一个项目可以具有特定的ID。如果您希望他们共享某些东西,请尝试使用它们。 由于

和具有相同的ID,因此它将不起作用 请注意,您可以获取Element S ByClassName,但只能获取 Element ById,其类允许多个且ID仅允许一个

答案 1 :(得分:2)

输入字段具有value属性。尝试更改此行: $("#country_name").val(response.country_name);

另外,就像@Khaleb所说的那样,元素ID必须是唯一的。

答案 2 :(得分:2)

您正在尝试使用.html()设置输入值。 jQuery不支持该功能。您需要使用.val()来设置输入值。 Here是相同的解释。

尝试一下:

<!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>

<script> 

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.country_name + ", " + response.region);
    $("#country_name").val(response.country_name);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");

</script>

</body>
</html>