简体   繁体   English

在jQuery或PHP中创建动态变量

[英]Creating a dynamic variable in jQuery or PHP

I know there are already a few questions like mine but I wasn't able to fix my problem with their solutions. 我知道已经有一些类似我的问题,但是我无法用他们的解决方案解决问题。

I got this code in an external html file to include it in others files: 我在外部html文件中获得了此代码,以将其包含在其他文件中:

<div class="header">
   <h1 class="replace-me">I'am a placeholder</h1>
</div>

The "file" above gets included into this "file": 上面的“文件”包含在此“文件”中:

<h2 style="display: none" class="variable">Hey, I'm a variable</h2>

The Variable from the second code should replace the content of the h1 tag in the first code. 第二个代码中的变量应替换第一个代码中h1标签的内容。 I know this isn't a forum to get free codes, I just want some inspirations or suggestions. 我知道这不是获得免费代码的论坛,我只想一些启发或建议。 Thanks Guys! 多谢你们!

If you have control over the external file, I'd suggest rewriting things so the external file serves a json object of some sort and work with your data from there. 如果您可以控制外部文件,我建议您重写一下内容,以便外部文件提供某种json对象并从那里处理数据。

Otherwise it's a simple matter of using JQuery to get the html contents from the variable and use that value to replace the html contents of the 'replace-me'. 否则,使用JQuery从变量获取html内容并使用该值替换“ replace-me”的html内容就很简单。

You can replace the html of one element with the html of another element, like so: 您可以将一个元素的html替换为另一个元素的html,如下所示:

 $(".replace-me").html($(".variable").html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="header"> <h1 class="replace-me">I'am a placeholder</h1> </div> <h2 style="display: none" class="variable">Hey, I'm a variable</h2> 

However, as Rama Schneider pointed out, you might want to get your content in a different way than html. 但是,正如Rama Schneider指出的那样,您可能希望以不同于html的方式获取内容。

Also note that this jQuery-solution is done client-side. 另请注意,此jQuery解决方案是在客户端完成的。 If you already know the content when serving the initial HTML, you want to do this server-side. 如果在提供初始HTML时已经知道内容,则需要在服务器端进行操作。

You should solve this on server-side if you can. 如果可以,您应该在服务器端解决此问题。 Make the common template a function, like this: 使通用模板具有功能,如下所示:

function getHeader($content) { ?>
<div class="header">
   <h1 class="replace-me"><?php echo $content; ?></h1>
</div> <?php
}

calculate $content before you call the function and pass it to the function . 在调用function之前计算$content并将其传递给function If you cannot make this a function and you get this as it is from a third-party source, then you can do it via Javascript, like this: 如果您不能将此function用作function而直接从第三方来源获得,则可以通过Javascript来实现,如下所示:

<script type="text/javascript">
    document.getElementsByClassName("header")[0].getElementsByClassName("replace-me")[0].innerHTML = "<?php echo $content; ?>";
</script>

Make sure you add this script after the header tag was loaded. 确保在加载标头标记后添加此script

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

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