简体   繁体   English

使用 PHP 语句填充元素的 innerHTML 的 JavaScript 函数不起作用

[英]JavaScript function to populate an element's innerHTML with a PHP statement not working

I'm trying to load a Bootstrap carousel only if the screen size is larger than 768px (larger than a mobile device), but having a little trouble with the JavaScript.仅当屏幕尺寸大于 768 像素(大于移动设备)时,我才尝试加载 Bootstrap 轮播,但在 JavaScript 方面遇到了一些麻烦。

I have the html element with the ID "hideIfScreenSmall" and an onload() event that fires the JS function loadCarousel() .我有 ID 为"hideIfScreenSmall"的 html 元素和一个触发 JS 函数loadCarousel()onload()事件。 The function is supposed to populate the <div> with HTML that two more nested <div> elements (the carousel and the photos in the carousel).该函数应该用 HTML 填充<div>两个嵌套的<div>元素(轮播和轮播中的照片)。 When I load my page, the carousel isn't showing up and I'm wondering if I have a simple syntax error that I can't spot (maybe with the escape characters?) or if there's a larger issue here.当我加载我的页面时,轮播没有显示,我想知道我是否有一个我无法发现的简单语法错误(可能是转义字符?),或者这里是否存在更大的问题。

<div id="hideIfScreenSmall" onload="loadCarousel()">
</div>

<script>
    function loadCarousel(){
        if(screen.width >= 768){
            document.getElementById("hideIfScreenSmall").innerHTML = "<div class=\"sectional_home-slider hidden-xs\"><div class=\"container full-md\"><?php echo do_shortcode('[rev_slider alias=\"comic_slider\"]');?></div></div>";
        }
    }
</script>

Is there something I'm writing wrong, or maybe an easier way to prevent a <div> from loading if the user is on a smart phone?如果用户使用的是智能手机,是否有什么我写错的地方,或者可能是一种更简单的方法来防止<div>加载? I'm not looking for a simple "display:none" fix because that still loads the element and just doesn't display it.我不是在寻找简单的"display:none"修复,因为它仍然加载元素并且只是不显示它。 I'm going for website optimization here.我要在这里进行网站优化。 I'm still pretty new to JS and PHP, so hopefully it's just an easy fix.我对 JS 和 PHP 还是很陌生,所以希望这只是一个简单的修复。 Thanks guys!谢谢你们!

UPDATE Thanks to @DanieleAlessandra I was able to get an image to populate the innerHTML .更新感谢@DanieleAlessandra,我能够得到一个图像来填充innerHTML However, it still won't populate with my PHP.但是,它仍然不会填充我的 PHP。 I've tried different variations of escape characters to no avail.我尝试了不同的转义字符变体,但无济于事。 Below is a link to a screenshot of the DevTools window and the code that's coming up on the other side.下面是 DevTools 窗口屏幕截图的链接,以及另一侧出现的代码。 Anyone know what I can do to make the PHP active?任何人都知道我可以做些什么来使 PHP 活跃?

Chrome DevTools Screenshot Chrome 开发者工具截图

You cannot use onload event on div , it doesn't work.您不能在div上使用onload事件,它不起作用。

You may use onload on body or you may want to attach a callback to document.ready event using jQuery:您可以在body上使用onload ,或者您可能想使用 jQuery 将回调附加到 document.ready 事件:

$(document).ready(function(){
   loadCarousel();
});

Or maybe without jQuery*:或者也许没有 jQuery*:

function ready(fn) {
  if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(loadCarousel);

Source of snippet: http://youmightnotneedjquery.com/片段来源:http: //youmightnotneedjquery.com/

Hello Danny the Hopeless ,你好无望的丹尼

My first tasks were related to the revision of the onload event in the div#loadThisWhenPageLoads element and as DanieleAlessandra pointed out this is not an effective approach.我的第一个任务与div#loadThisWhenPageLoads元素中的 onload 事件的修订有关,正如DanieleAlessandra指出的那样,这不是一种有效的方法。

Next, in reviewing your question thoroughly, I realized that your actual goal here seems to be merely able to achieve the functionality that shows and removes a Bootstrap carousel depending on the screen size .接下来,在彻底审查您的问题时,我意识到您在这里的实际目标似乎只是能够实现根据屏幕大小显示和删除 Bootstrap 轮播的功能 Now that is a different task altogether in my view.现在,在我看来,这是一项完全不同的任务。 With that said, I think an approach that leverages the CSS3 display property and @media queries is the most practical and effective way to resolve the task at hand.话虽如此,我认为利用 CSS3 显示属性和 @media 查询的方法是解决手头任务的最实用和最有效的方法。 Below you can find the code I created for this particular purpose.您可以在下面找到我为此特定目的创建的代码。


JSFiddle Resolution Demo : JSFiddle 解析演示

JSFiddle link demo JSFiddle 链接演示


Full Code Snippet :完整代码片段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!--
        Bootstrap CSS Loaded from CDN.
        Note: You can load the Bootstrap CSS from anywhere you want (CDN, locally, etc.). In my case, I am using a CDN as it is easy to implement so I can quickly move on and work on what matters -resolving the issue at hand.
    -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Arty's StackOverflow Question 56740953</title>
</head>
<body>

<h1>StackOverflow Question 56740953 Resolution</h1>

<h2>Goal</h2>

<p>
    Load a Bootstrap carousel only if the screen size is larger than 768px (larger than a mobile device).
</p>

<h3>Basic Approach (CSS3 display/media-query):</h3>

<ol>
    <li>Load hidden carousel (display: none). </li>
    <li>Use CSS3 media query to show carousel when screen size is larger than desired with (768px).</li>
</ol>

<h2>Resize browser screen to see demo in action:</h2>

<style>
/*
** Micro-style choice to improve body visibility.
** Remove this style script when ready to use and resize body as needed.
*/
body {
    padding: 20px;
}
/*
** Micro-style choice to reduce slider size for this demo.
** Remove this style script when ready to use and resize carousel as needed.
*/
#carouselExampleIndicators {
    width: 80vh;
    margin: 0 auto;
}
</style>

<!--
    Bootstrap Carousel Example With indicators.
    Source: https://getbootstrap.com/docs/4.0/components/carousel/
    Note: I am using "placeimg" to load dummy images easily for this demo.
    Source: https://placeimg.com/
-->
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
    <div class="carousel-item active">
    <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="First slide">
    </div>
    <div class="carousel-item">
    <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="Second slide">
    </div>
    <div class="carousel-item">
    <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="Third slide">
    </div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
</a>
</div>

<style>
#carouselExampleIndicators {
    display: none;
}
@media screen and (min-width: 768px) {
    #carouselExampleIndicators {
        display: block; /* "block" is the default display property value for this Bootstrap carousel div. */
    }
}
/*
    The following sources are recommended concerning the CSS3 display property and @media queries. Also,please note that the order matters when it comes to the @media queries so moving the @media... piece of code arbitrarily anywhere before the code that defines the styles for the elements referred within the @media styles can affect the functionality detrimentally.
**
** Source: https://www.w3schools.com/css/css_display_visibility.asp
** Source: https://www.w3schools.com/css/css3_mediaqueries.asp
*/
</style>

<!--
    Bootstrap JavaScript Bundle Loaded from CDN.
    Note: You can load the Bootstrap CSS from anywhere you want (CDN, locally, etc.). In my case, I am using a CDN as it is easy to implement so I can quickly move on and work on what matters -resolving the issue at hand.
    Source: https://www.bootstrapcdn.com/
-->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>

</body>
</html>

This as certainly an interesting challenge.这当然是一个有趣的挑战。 If you have any issues implementing the approach I have recommended please feel free to let me know and I would be glad to assist you further.如果您在实施我推荐的方法时遇到任何问题,请随时告诉我,我很乐意为您提供进一步的帮助。 Also, if for whatever reason you are interesting in continuing to seek an approach that is related loading the carousel element via Javascript and/or inserting PHP code dynamically to accomplish this end, let me know as well and I would look into this matter further with you.此外,如果出于某种原因,您有兴趣继续寻求一种与通过 Javascript 加载轮播元素和/或动态插入 PHP 代码相关的方法来完成此目的,也请告诉我,我将进一步研究此事你。 There are certainly many paths to web development and the CSS3 approach seemed the most straightforward for the challenge you have at hand, which is why I have recommended it, but I am happy to help you look into other alternate solutions that might better suit your specific needs. Web 开发肯定有很多途径,CSS3 方法对于您手头的挑战似乎是最直接的,这就是我推荐它的原因,但我很乐意帮助您寻找可能更适合您的特定情况的其他替代解决方案需要。

Regards,问候,

Arty艺术

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

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