简体   繁体   中英

how to get value from a html using external javascript

I have two javascript files, js1 and js2. js1 is defined in index.jsp. and inside js1 i'm using js2. once i'm executing js2 i want to take some values from index.jsp. (js2 can't define in ndex.jsp file) so, How can i access html using this external js file (js2)

this is my index.jsp

    <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="js1.js"></script>
</head>
<body>
    <h1>test</h1>
    <span id="up"></span>test<br><br><span id="down"></span>
    <br><br>
    Time : <span id="foo"></span>
    <br><br>
    <div id="uid" >this is the value i want to access</div>
    <button onclick="start()">Start sync</button>
    </body>

this is js1.js

navigator.serviceWorker.register('js2.js', { scope: '/login/' }).then(function(reg) {
    if(reg.installing) {
      console.log('Service worker installing');
    } else if(reg.waiting) {
      console.log('Service worker installed');
    } else if(reg.active) {
      console.log('Service worker active');
    }
    //setTimeout(refresh, 10000);
  }).catch(function(error){
      console.log('Registration failed with ' + error);
  });

this is js2.js

var eventSource2 = new EventSource("HelloServlet");
eventSource2.addEventListener('down_vote',function(event){
    console.log("data from down" , event.data);
    var MyDiv1 = document.getElementById('uid'); //this is not working
    var val = MyDiv1.innerHTML; //this is not working
    console.log(val + "ddddd 2"); //this is not working
    console.log("down");
});

There is a mystery variable index

var MyDiv1 = index.getElementById('uid'); //this is not working

should probably be

var MyDiv1 = document.getElementById('uid'); 

You are including js1.js at the beggining of you main page, so it can't find the DOM elements of index.jsp

You should include js1.js at the end of index.jsp

or include it in document.ready() of index.jsp

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>
    <h1>test</h1>
    <span id="up"></span>test<br><br><span id="down"></span>
    <br><br>
    Time : <span id="foo"></span>
    <br><br>
    <div id="uid" >this is the value i want to access</div>
    <button onclick="start()">Start sync</button>

    <script type="text/javascript" src="js1.js"></script>
</body>

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