简体   繁体   English

如果使用javascript括号则打开

[英]open if bracket in javascript

I'm trying to execute a HTML code if there is variable in JS, is there something like in PHP, where you can use 我正在尝试执行HTML代码,如果JS中有变量,是否有类似PHP的东西,您可以在其中使用

<?php
if ($variable == True) { ?>
<img src="image.jpg">
<?php } else { ?>
<img src="image2.jpg">
<?php } ?>

so in JS 所以在JS中

<script>
if (variable == true) {
</script>
<img src="image.jpg">
<script>
} else {
</script>
<img src="image2.jpg">
<script>
}
</script>

or it has to been done like this 或必须像这样完成

<script>
if (variable == true) {
$("#element").prepend("<img src='image.jpg'>");
} else {
$("#element").prepend("<img src='image2.jpg'>");
};
</script>

Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/ 问题是如果我使用prepend或innerHTML插入我的“图像”,即单击图像后调用的函数-image.addEventListener('click',function() stop work:/

Thank you :) 谢谢 :)

Well last one is correct one but you can simplify it: 好吧,最后一个是正确的,但是您可以简化一下:

var src = variable === true ? "image" : "imgage2";
$("#element").prepend('<img src="'+ src +'.jpg">');

Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/ 问题是如果我使用prepend或innerHTML插入我的“图像”,即单击图像后调用的函数-image.addEventListener('click',function()stop work:/

That could be because of dynamically element's creation, you can sort it out with event delegation. 那可能是由于动态元素的创建,您可以使用事件委托对其进行分类。

With jQuery: 使用jQuery:

$('#element').on('click', 'img', function(e){
     // put code here
});

With javascript it is little bit different, .querySelectorAll() returns a collection with is array like object, so iteration needs to be there, Collection.forEach(cb) can be used to bind the event: 与javascript稍有不同, .querySelectorAll()返回的集合类似于is对象的数组,因此需要迭代, Collection.forEach(cb)可用于绑定事件:

var imgs = document.querySelectorAll('#element img');
Array.forEach.call(imgs, function(img){
  img.addEventListener('click', function(){
    // put code here
  });
});

And with js all the events are delegated events. 而使用js,所有事件都是委托事件。

Try this: 尝试这个:

<script>
    if (variable == true) {
        $("#element").attr('src', 'image.jpg');
    } else {
        $("#element").attr('src', 'image2.jpg');
    };
</script>

Comment: 评论:
This will only change the picture attribute , not the entire <img... /> element. 只会更改picture属性 ,而不更改整个<img... />元素。 So, events attached to the img element will be preserved . 因此, 将保留img元素附带的事件

I assume that you want to check if your variable is boolean and you want to check if it is true. 我假设您要检查变量是否为布尔值,并且要检查其是否为真。 Also i assume that you have several images and you want to prepend new one to them, then you could do: 我也假设您有几张图像,并且想要在它们之前添加新的图像,那么您可以执行以下操作:

Create hidden div on the page, Something like this: 在页面上创建隐藏的div,如下所示:

<div id="htmlToDomCreator" style="position: absolute; top: 0; left: 0; width: 1px; height: 1px; visibility: hidden;" >
</div>

Inside your javascript code do something like this: 在您的JavaScript代码中执行以下操作:

<script>

    var htmlToDomCreator = document.getElementById('htmlToDomCreator');
    var yourElement = document.getElementById('element');

    var htmlTag = "";

    if (variable == true) {
        htmlTag ="<img src='image.jpg'>";
    } else {
        htmlTag ="<img src='image2.jpg'>";
    }

    htmlToDomCreator.innerHTML = htmlTag;

    var myImgTag = htmlToDomCreator.firstChild;

    if(yourElement.firstChild){
        yourElement.insertBefore(myImgTag, yourElement.firstChild);
    }else{
        yourElement.appendChild(myImgTag);
    }

    myImgTag.onclick = function() {
        // do click stuff here
    };

</script>

The idea is that whether you use innerHTML or prepending string with jquery, you have to take whole innerHTML, prepend string to it and then reinsert whole content again. 这个想法是,无论您使用innerHTML还是在jquery前面加上字符串,您都必须获取整个innerHTML,在其前面加上字符串,然后再次重新插入整个内容。 As you undoubtedly can see, this "kills" all handlers added from javascript and you have to reattach them again. 毫无疑问,这会“杀死”从javascript添加的所有处理程序,因此您必须重新附加它们。

To avoid this, we create dom from string "somewhere else" and then prepend it as a dom child element. 为避免这种情况,我们从字符串“ somewhere else”创建dom,然后将其作为dom子元素放在前面。

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

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