Javascript-如何将值传递到Javascript代码中
我在尝试将值转换为javascript并将其传递给alert时遇到了很多麻烦。下面是我用来传递值的代码Javascript-如何将值传递到Javascript代码中,javascript,jquery,Javascript,Jquery,我在尝试将值转换为javascript并将其传递给alert时遇到了很多麻烦。下面是我用来传递值的代码 <img onclick="handpost()" id="colorface" name="red" src="http://www.asl-ela.org/image/redface.png" alt="Red face" /></a> 然后我使用函数从img标签获取数据 <script type="text/javascript">
<img onclick="handpost()" id="colorface" name="red" src="http://www.asl-ela.org/image/redface.png" alt="Red face" /></a>
然后我使用函数从img标签获取数据
<script type="text/javascript">
function handpost() {
var color = document.getElementById('colorface').name;
alert(color);
}
</script>
函数handpost(){
var color=document.getElementById('colorface').name;
警报(颜色);
}
我一直收到警告框说未定义。那是什么意思 它的意思就是:
document.getElementById('colorface')。name
未定义document.getElementById('colorface')
可能存在,但它没有属性name
。尝试document.getElementById('colorface').getAttribute('name')
name
不是img
的标准属性,但如果添加它,则可以访问它。
请改用以下方法:
var color = document.getElementById('colorface').getAttribute('name');
不确定如何将其作为
未定义的
Element.name,name
获取或设置DOM对象的name属性;它仅适用于以下元素:)
函数handpost(){
var color=document.getElementById('colorface').name;
警报(颜色);
}
名称
不是
属性实体名称
是img元素的属性。您应该使用getAttribute
获取其值,请尝试使用文档.getElementById('colorface').getAttribute('name')
因为name
不是img
属性的标准属性,所以不应该使用它。相反,最好将data name
作为一个整体使用data-*
realm,因为它是为自定义值保留的。。这些值也可以通过jQuery的data
方法或getAttribute('data-name')
访问。我将name
更改为。getAttribute('name')
,效果很好。嗨,Alex,我确实使用了您建议的代码。我试过了,警报框显示为空。我在jfiddle中试过,它的工作原理是红色的。那么到底发生了什么?谢谢