2017-09-23 54 views
-1

我正在嘗試製作一個名爲id ='pr'的圖像。 我的HTML代碼在javascript中製作HTML id變量

<div id="main"> 
<img id ='pr' style="width: 500px;height: 600px;"src="https://i.redd.it/2u0y0z5i12py.png"> 
</div> 

我的JavaScript代碼:

<script type="text/javascript"> 
    var getElementById('pr') = 1 
    if (getElementById('pr' = 1)) {alert ('im pickle rick bitch')} 
    </script> 

那麼,我試圖做的是使一個變量PR,並給它一個的值,所以它觸發如果PR警報是畫廊中的形象。我很好地解釋了它的好處,因爲我的英語不是最好的!(我也是小菜鳥)TY!

+2

已標記爲正確的答案,是不正確的。請參閱下面的答案。 –

回答

0

試試這個:

var foo = document.getElementById('pr'); 

if (foo) {alert ('im pickle rick bitch')} 

這將解決您的問題與運行的代碼,如果你的ID存在,纔會顯示。但我建議你看看一些JavaScript教程。這將有助於您更好地理解Suren Srapyan的答案。

+1

現在您的答案實際上不會解決OP問題,因爲警報將在每種情況下顯示。 –

0

您可以爲img設置一個值,但據我所知您需要在img標記上添加一些額外的信息。您可以通過setAttributegetAttribute方法來完成。

在你的代碼中你有一些錯誤。你的變量聲明是錯誤的。你需要給你的變量一個名字,在我的情況下它是myPr,併爲它分配返回document.getElementById的不只是getElementById的vlaue。然後使用setAttribute方法來設置一些名爲dataId的HTML5約束屬性。之後,您可以使用getAttribute方法來獲取該值並在邏輯中使用。

const myPr = document.getElementById('pr'); 
 
myPr.setAttribute('dataId', 1); 
 

 
if(Number.parseInt(myPr.getAttribute('dataId')) === 1) { 
 
    alert ('im pickle rick *****'); 
 
}
<div id="main"> 
 
<img id ='pr' style="width: 500px;height: 600px;"src="https://i.redd.it/2u0y0z5i12py.png"> 
 
</div>

+0

是的,但它只需要激活,如果它的圖像,如果它的另一個它不需要說im im picke裏克 – mikailavci2

+0

是的,根據我們設置的屬性值,你可以編寫你的邏輯。獲取與您想要的比較的屬性。 –

+0

ooooh所以我可以編輯dataid我是嗎? – mikailavci2

1

您的主要問題是,如果您爲pr創建變量,然後將該變量設置爲1,那麼您將失去對pr的引用。

換句話說:

var document.getElementById("pr") = 1; 

無效代碼,因爲你沒有指定變量名。但是,即使你沒有:

var x = document.getElementById("pr") = 1; 

x將在第一持有參考pr,然後立即失去價值,而是被設置爲1

您的if條件也有問題,因爲單個等號(=)用於設置值,而不是比較兩個值。所以,你的情況總是會返回true。 JavaScript使用=====進行比較。

如果您需要一種方法來保持元素的軌道,你可以給每個元素下方所示的data-* attribute爲:

var element = document.getElementById('pr'); 
 
// We can extract the data-count attribute value (a string) 
 
// with the .dataset.count property: 
 
if (element.dataset.count === "1") { 
 
    alert ('im pickle rick bitch'); 
 
}
<div id="main"> 
 
    <!-- The data-* attributes are designed to allow you to store meaningfull data with an element. --> 
 
    <img id ='pr' data-count="1" 
 
     style="width: 500px;height: 600px;" src="https://i.redd.it/2u0y0z5i12py.png"> 
 
</div>