如何在javascript中获取HTML元素的值? [英] How to get value of HTML element in javascript?

查看:27
本文介绍了如何在javascript中获取HTML元素的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在获取代码中特定字段的值时遇到了麻烦 - 我做了这个非常简单的例子来展示我的问题,这里是 JSFiddle:https://jsfiddle.net/c3jtg60v/

so I'm having trouble with getting the value of a specific field in my code - I made this pretty simple example to show my problem, here is the JSFiddle: https://jsfiddle.net/c3jtg60v/

HTML:

<p id="theInput">
   desired-value
</p>

Javascript:

The Javascript:

var value = document.getElementById("theInput").value;
console.log(value);

按原样,我已经分配了一个 ID 为theInput"的 p 元素,其中我有想要的值,我想在我的 javascript 中使用它.

As is, I have assigned a p element with an id of "theInput", and in it I have the desired value, that I want to make use of in my javascript.

目前,我所做的只是在 console.log 中记录值,但是当我这样做时,我在控制台中登录的只是未定义".我真正想记录到控制台的是期望值",

At the moment, all I'm trying to do is console.log the value, but when I do this, all i get logged in the console is 'undefined'. What I really want to get logged to the console is "desired value",

对此的任何帮助将不胜感激!

Any help on this would be greatly appreciated!

我喜欢我如何得到很多反对票,人们向我提出的问题是将innerhtml值放入变量中"-问题是我不知道innerHTML,我怎么知道那个问题有关系吗??来人吧!

I like how I get lots of downvotes, and the question people are sending me to, is "Getting innerhtml value into the variable" - The problem was I didn't know about innerHTML, how would I know that question is relevant?? come on people!

推荐答案

.value 指的是 value 属性,不能为 P 标签.如果你想要 html 标签的内部文本,你可以这样做:

.value refers to a value property, which cannot be set for a P tag. If you want the inner text of a html tag, you could do this:

var value = document.getElementById("theInput").innerHTML;

这篇关于如何在javascript中获取HTML元素的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆