繁体   English   中英

使 HTML id 成为 javascript 中的变量

[英]making HTML id a variable in javascript

我正在尝试使名为 id='pr' 的图像成为这样的变量。 我的 HTML 代码是

<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!

您的主要问题是,如果您为pr创建一个变量,然后将该变量设置为1 ,您将丢失对pr的引用。

换句话说:

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

不是有效代码,因为您没有指定变量名称。 但是,即使你做了:

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

x将首先持有对pr的引用,然后立即失去该值并设置为1

您的if条件也有问题,因为单个等号 ( = ) 用于设置值,而不是比较两个值。 因此,您的条件将始终返回true JavaScript 使用=====进行比较。

如果你需要一种方法来跟踪元素,你可以给每个元素一个data-* 属性,如下所示:

 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>

您可以为img设置一个值,但据我所知,您需要在img标签上添加一些额外信息。 您可以通过setAttributegetAttribute方法来实现。

在您的代码中,您有一些错误。 你的变量声明是错误的。 你需要给你的变量一个名字,在我的例子中它是myPr并分配给它的 vlaue 返回document.getElementById而不仅仅是getElementById 然后使用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>

尝试这个:

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

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

这将解决您运行代码的问题,并且只会显示您的 ID 是否存在。 但我建议你看看一些 javascript 教程。 这将帮助您更好地理解 Suren Srapyan 的回答。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM