简体   繁体   中英

How to add HTML code to a different HTML file using JavaScript or PHP

Alrighty, so I am trying to make a little page on my website that takes a few values and then when you click a button, it adds those values inside of a div on a different HTML page.

My code is:

<input type="text" name="URL"><br>
<input type="text" name="ImageURL"><br>
<input type="text" name="Title">
<button onclick="addCode()">Submit</button>

So for the addCode() function I want it so that it adds the values inside of a the item div on a different HTML file just like:

<div class="item">
   <div class="animate-box">
      <a href=URL><img src=ImageURL></a>                
      <div class="fh5co-desc"><a style="TEXT-DECORATION:none; COLOR:#818892; LINE-HEIGHT:20px;" href=URL>Title</a></div>
   </div>
</div>

Thanks in advance.

The only way to do this (without getting other technologies involved) is to use the localStorage , storage event. And, even with this, it will only work when the two pages are coming from the same domain and are open in different browser tabs (of the same browser) at the same time.

If those conditions are present, then modifying localStorage on one page will fire the storage event, which the other page can be set up to listen for. The other page can then respond to the event by pulling new values (that the first page wrote into localStorage ) out and placing them anywhere on the second page that you like.

This is the kind of solution that you might encounter if you were on a travel site with more than one browser tab open. You may be looking at different flight options in different tabs. If one tab's code has an update that any/all other open tabs should know about, this technique does the trick.

Here's an example of how to set values into localStorage and use them. But, localStorage doesn't work here in the Stack Overflow snippet environment, so you can run the code here .

Once the values are in localStorage , you can pick them up from any other page that is being served from the same domain. So, the "getItem" code I'm showing here would really be placed on your "page2.html".

 // Get DOM references: var name = document.getElementById("name"); var color = document.getElementById("color"); var airspeed = document.getElementById("airspeed"); var btn = document.getElementById("btnGo"); // Set up button click event handler: btn.addEventListener("click", function(){ // Get values and place in localStorage localStorage.setItem("name", name.value); localStorage.setItem("color", color.value); localStorage.setItem("airspeed", airspeed.value); // For demonstration, get values out of localStorage console.log("What is your name? ", localStorage.getItem("name")); console.log("What is your favorite color? ", localStorage.getItem("color")); console.log("What is the airspeed of a laiden swallow? ", localStorage.getItem("airspeed")); // If you wanted to redirect the user to the second page, now that the intial values // have been set, you could just do: location.href = "path to second page"; }); 
 <div>What is your name?<input type="text" id="name"></div> <div>What is your favorite color?<input type="text" id="color"></div> <div>What is the airspeed of a laiden swallow?<input type="text" id="airspeed"></div> <button id="btnGo">Go!</button> 

What you are doing is technically impossible. without some sort of persistence, that is;

you cannot edit a page you aren't on. web browsing is a stateless technology.

if you meant you want to fill out those inputs then redirect on click and have those values available, there are a few different ways to do it:

1) Query String

write your code on the second page in a way that it accepts params from a query string in the url bar

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

var textDecoration = getUrlParameter('textdec'),
    color = getUrlParameter('color'),
    lineHeight = getUrlParameter('lnheight');

then you can send the request for the page as

http://page.com/page?textdec="someval"&color="somecolor"&lnheight="someheight"

however this will not work if you are not going directly to that page after your current one

2) localStorage

on your first page set the local storage values:

localStorage.setItem('lineHeight', 'someVal');
localStorage.setItem('color', 'someColor');
localStorage.setItem('textDecoration', 'someVal');

then on your second page retrieve the values

var lineHeight = localStorage.getItem('lineHeight'),
    color = localStorage.getItem('color'),
    textDecoration = localStorage.getItem('textDecoration');

3) serverSide persistence

this will vary MASSIVELY depending on how you your backend is structured

but the general gist is make a post request (ajax or otherwise) & collect the data on the backend

then when you render the second page send the variables that were posted, either through interpolation or included as script variables

If you're trying to edit the actual source code of the file, you'll need something like PHP. Otherwise, JS is just fine.


PHP Solution

You could use something like this:

 <?php $old = file_get_contents("some_page.html"); $content = explode("<span>",$old,2); // replace <span> w/ opening tag $content = explode("</span>",$content[1],2); // replace </span> w/ closing tag $data = "new content of element"; $new = str_replace($content[0],$data,$old); ?> 

Updated JS Solution

You can't use my previous solution. Instead, you would have to create a function in the second HTML file that could be called from the first file, like this: A script in file2.html:

 function set(id,val){ $("#"+id).html(val); // jQuery document.getElementById(id).innerHTML = val; // pure JS } 

A script in file1.html:

 var win = window.open("http://example.com"); // open the window win.set("some_id","Some content.") // the function that we set earlier 

Note that this is reverted once the user closes or reloads the tab, and only applies to that user and that tab.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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