[英]Get the value of HTML class, then put in in an input element
I've been trying to get the value of the ip address, which is already inside <p id='details'></p>
to be put in the value of the input html class as well found on the last line.我一直在尝试获取 ip 地址的值,该地址已经在
<p id='details'></p>
中,以便放入输入 html ZA2F2ED4F8EBC2CBB14C21A29DC40 上的值中。
I tried declaring it as a php variable but I couldn't afford so.我尝试将其声明为 php 变量,但我负担不起。
<script>
var ipinfo;
$.getJSON("https://ipinfo.io", function (data) {
$("#details").html(data.ip)
})
</script>
<p id='details'></p>
<input type="text" name="ip" class="" value="@php echo ""; @endphp" readonly>
You can firstly get hold of the content of a particular HTML class by copying over the value into a variable, and then inject this value by assigning the copied over variable's value into the input's value.您可以首先通过将值复制到变量中来获取特定 HTML class 的内容,然后通过将复制的变量值分配给输入值来注入该值。 You could achieve this by using plain Vanilla JavaScript.
您可以通过使用普通的 Vanilla JavaScript 来实现这一点。
Since your p
tag is initially empty and the data is injected into the p
tag after it is fetched from a network, this process becomes an asynchronous task.由于您的
p
标签最初是空的,并且在从网络获取数据后将数据注入p
标签,因此该过程成为异步任务。 So, you'd want to feed the data only after it is fetched, so you can add the value assigning logic within the fetch function as follows:因此,您只想在获取数据后才提供数据,因此您可以在 fetch function 中添加值分配逻辑,如下所示:
var ipinfo;
$.getJSON("https://ipinfo.io", function (data) {
document.querySelector("#details").innerHTML = data.ip
const inject = document.querySelectorAll("input[type=text]")[0] //Identify the input element
inject.value = data.ip //Assign the returned value to input's value.
})
As you want the returned value from fetch to be fed to the p
tag content as well as the input tag value, you could directly assign it, instead of copying over the already copied value.由于您希望将 fetch 的返回值馈送到
p
标签内容以及输入标签值,因此您可以直接分配它,而不是复制已经复制的值。
From what i Can see you just need a token.从我可以看到你只需要一个令牌。
Also, I've used ES6 fetch method to get the API object response另外,我使用 ES6 获取方法来获取 API object 响应
fetch('https://ipinfo.io/json?token=e0b12a7d02537a').then( (response) => response.json() ).then( (jsonResponse) => { //this will display the IP as ap elemenet text $('#details').html('IP Address = ' + jsonResponse.ip) //here we are assigning it as a value to the input $('input[name="ip"]').val(jsonResponse.ip); } )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id='details'></p> <input type="text" name="ip" class="" readonly>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.