2011-12-24 69 views
0

我試圖獲取這是在MySQL數據庫中的id值。但是,每次點擊圖片時,我都會收到null。我使用this來獲得價值,但它不工作,因爲它不斷給我在警告框中null將值從PHP傳遞到JavaScript

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <?php 
     mysql_connect('localhost','root',''); 
     mysql_select_db("ajax"); 
     $query="SELECT * FROM xxxx"; 
     $result= mysql_query($query); 

     while($row= mysql_fetch_array($result)){ 
      echo "<img src='".$row['filepath']."' value='".$row['ID']."' id='".$row['ID']."' onclick='getrating(this.value);'>"; 

      echo "<br>"; 
     } 
    ?> 

    <script type="text/javascript" > 
     function getrating(row_id){ 
      var x = document.getElementById(row_id); 
      alert(x); 
     } 
    </script> 
</body> 
</html> 

什麼問題?

+0

你是如何調用函數的? – 2011-12-24 18:29:37

+0

HTML的外觀如何?這是預期的嗎?如果是這樣,JavaScript函數中的row_id是什麼?什麼是x?這是否如預期的那樣?調試從你開始。 (另外,如果您只需要傳遞值,則沒有理由使用DOM元素節點。) – 2011-12-24 18:29:56

+0

您認爲圖像可能具有什麼「價值」?我會認爲你會發現''[沒有值屬性](http://www.java2s.com/Code/HTMLCSSReference/HTML-Tag-Reference/imgJavaScriptProperties.htm)。 – vascowhite 2011-12-24 18:34:48

回答

4

你需要getrating(this.id)代替。圖像沒有value屬性。

+0

非常感謝。我不知道該怎麼感謝你才足夠。 – mayank23 2011-12-24 18:36:44

2

試試這個:

echo "<img src='".$row['filepath']."' id='".$row['ID']."' onclick='getrating(".$row['ID'].");'>"; 
+1

如果行ID值與表單某處的另一個ID相同,那麼這不會允許重複的元素ID? – Nonym 2011-12-24 18:35:12

+0

我這樣做,並得到[對象HTMLImageElement],所以然後我在這裏增加值,「var x = document.getElementById(row_id).value;」但現在我變得不確定。你能幫忙嗎?謝謝 – mayank23 2011-12-24 18:35:16

+0

@ mayank23你的元素是一個IMG,正如我所說,IMG標籤沒有「值」屬性。你可以使用id本身,也可以使用數據字段。既然你所追求的「價值」與你使用的ID一樣,但它似乎是一個多餘的步驟。 – 2011-12-24 18:39:40

0

value不是img標籤的有效屬性。您可以使用id,或者只是做

echo "<img ... onclick='getrating($row[ID]);'>"; 
+0

如果行ID值與表單中某處的另一個ID相同,這不會允許重複的元素ID? – Nonym 2011-12-24 18:35:40

+0

沒有比'id ='「。$ row ['ID']。」''更好的了,但那是另一個問題。 – 2011-12-24 18:37:07

+0

另一個問題,但仍然如此,雖然..mayank23應該儘量避免使用'id'作爲'id'的值,除非它不可能在代碼 – Nonym 2011-12-24 18:43:56

1

或者你也可以通過this.id

<img id="row_12" onclick="getrating(this.id)" alt="image"/> 



function getrating(id){ 
    alert(id); 
} 

或者你也可以使用事件對象和currentTarget當前歡迎使用屬性

<img id="row_12" onclick="getrating(event)" alt="image"/> 



function getrating(e){ 
    alert(e.currentTarget.id); 
} 
0

<img>不具有價值屬性。

你也在你的功能上做了不必要的工作。您的代碼應該是這樣的: -

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <?php 
     mysql_connect('localhost','root',''); 
     mysql_select_db("ajax"); 
     $query="SELECT * FROM xxxx"; 
     $result= mysql_query($query); 

     while($row= mysql_fetch_array($result)){ 
      echo "<img src='".$row['filepath']."' value='".$row['ID']."' id='".$row['ID']."' onclick='getrating(this);'>"; 

      echo "<br>"; 
     } 
    ?> 

    <script type="text/javascript" > 
     function getrating(element){ 
      alert(element); 
     } 
    </script> 
</body> 
</html> 

通過傳遞this你的函數通過onclick事件,你已經擁有你無需使用document.getElementById()尋找的元素。

0

他們的方式如何逃避身份證可能是問題。我知道這已經得到解答,但只是爲了那些需要另一種解決方案的人。

onclick="getrating(\''.$row['ID'].'\')"