当前位置: 动力学知识库 > 问答 > 编程问答 >

html - send a value with onclick on a image in javascript

问题描述:

I want to send a value using image and onclick for js. but my function is not working because i can't define value in img tag maybe then how can i send this value to my function.It must show image and when i click image it will send a constent value to a js function.

It's something like

 <img src="img/sit.png" value="<?php echo $data[1];>"onclick="choose(this.value);"/>

I used js

 function choose(idval){

alert(get.ElementById(idval));

}

But it is not working

The value may use for ajax in js give example if you can.

please help.

网友答案:

Try this

<html>
<head>
<title>thumbs</title>
<script>
function sendimg(a)
{
window.location.href='b.html#id='+a.id+'&src='+a.src;
}
</script>
</head>
<body>
<img src="imgs/img1.jpg" id="img1" onClick="sendimg(this);">
<img src="imgs/img2.jpg" id="img2" onClick="sendimg(this);">
</body>
</html>

Image HTML

<html>
<head>
<title>img</title>
 <script>
 function getimg()
 {
  var a=window.location.href.split('#')[1].split('&'),
  id=a[0].split('=')[1],
  src=a[1].split('=')[1],
  img=document.images[0];
  img.id=id;
  img.src=src;
  }
 </script>
 </head>
 <body onLoad="getimg()">
 <img src="ablankimage.gif">
 </body>
</html>
网友答案:

HTML:

<img id="catImage" src="http://i.imgur.com/Mmfl8.png" width="100px" value="42" />
<div id="catImageValue"></div>

JavaScript:

var catImage = document.getElementById("catImage"),
    catImageValue = document.getElementById("catImageValue");

catImage.onclick = function () {
    catImageValue.innerHTML = "Value = " + catImage.getAttribute("value");
};

http://jsfiddle.net/koldev/6K2bp/ <= Click on the cat!

网友答案:

Use data-attributes along with jquery

<img id="myImg" src="img/sit.png" data-myvalue="<?php echo $data[1];?>" onclick="doSomething();"/>

and then with jQuery in your doSomething() method you can get the value like this:

 $("#myImg").data("myvalue") 
网友答案:

try this

<img src="img/sit.png" value="somevalue" onclick="choose(this);"/>
<script>

function choose(element){
    alert(element.getAttribute("value"));
} 
</script>

here is the fiddle http://jsfiddle.net/FC6sq/1/

分享给朋友:
您可能感兴趣的文章:
随机阅读: