JQuery и JS работает на DOM, а не onLoad

0

Во-первых, позвольте мне начать с того, что я не знаю много о javascript и особенно JQuery

У меня возникла проблема с загрузкой javascript и Jquery на моей странице.

1) Я создал некоторый код здесь на скрипте JS http://jsfiddle.net/Gilera/mT9pV/1/. Существует несколько javascript для преобразователя часового пояса и функция JQuery для разворота экрана hide/show.

Код отлично работает при использовании jsfiddle onDomready и отображает как время, так и скользящее действие скрытых div. Но при использовании onLoad скрытый div работает, но не преобразователь часового пояса. Любая идея, как я могу заставить оба запускать при использовании onload mode на js скрипке?

2) Также, если я скомпилирую код и тестовый веб-сайт в браузере, я получаю противоположное, что Times загружает, но не скрытые divs при нажатии на них. как я могу, возможно, изменить скрипт chan2.js для запуска, возможно, как onDomready или мне нужно добавить скрипт выше, чтобы найти JQuery Libary?

Я прошу прощения за длинный пост с текстом te, но это все ново для меня, и любая помощь будет очень признательна.

Ниже приведен код im, использующий

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="style2.css" rel="stylesheet" type="text/css" />


</head>

<div class="schedule"><div class="event"><ul class="guides"><li class="icon"><img src="" alt="" width="26" height="27" class="icon"/></li><li class="time"><span data-utc="9:05"></span></li><li class="game">Team A vs Team B</li></ul></div><div class="place"><ul class="venue"><li class="field">Field A</li></ul></div></div>

<div class="schedule"><div class="event"><ul class="guides"><li class="icon"><img src="" alt="" width="26" height="27" class="icon"/></li><li class="time"><span data-utc="9:05"></span></li><li class="game">player A vs Player B</li></ul></div><div class="place"><ul class="venue"><li class="field">Court 3</li></ul></div></div>

<div id='out'></div>  
<script type='text/javascript' src='times2.js'></script>
<script type='text/javascript' src='chans2.js'></script>
<body>
</body>
</html>

CSS style2.css

@charset "utf-8";
.event {
width: 600px;
height: 38px
}

.place{
display: none;
width: 590px;
height: 38px;
text-align: center;
font-size: 12px;
font-weight: bold;
color: #EB1D2D;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

ul.guides {
width: 570px;
height: 34px;
list-style: none;
display: block;
background-color: #D1E5FD;
border-style: solid;
border-width: 1px;
border-radius: 2px;
border-color: black;
border-spacing: 5px;
padding-top:1px;
border-radius:5px
}
ul.guides a, ul.guides a:visted, ul.guides a:link {
display: block;
text-decoration: none;
background-color: #8090AB;
color: black;
}
ul.guides a:hover, ul.guides a:active, ul.guides a:focus {
background-color: #FFFFFF;
}

li.icon {

display: inline-block;
width: 24px;
height: 24px;
padding-left: 10px;

}
img.icon{
display:inline-block;
padding-top:3px;
}
li.time{
display:inline-block;
text-align:center;
font-size: 12px;
width: 70px;
padding-left: 5px;
color: #0000FF;
font-family: Tahoma, Geneva, sans-serif;
font-weight: bold;


}
li.game{
display: inline-block;
text-align:center;
font-size: 12px;
padding-left: 10px;
background-color: #D1E5FD;
text-decoration: none;
font-family: Tahoma, Geneva, sans-serif;
font-weight: bold;
}
ul.guides a, ul.nav a:visted{
display: block;
text-decoration: none;
background-color: #8090AB;
color: #000;
}

ul.guides a:hover, ul.guides a:active, ul.guides a:focus{
background-color: #6F7D94;
color: #000;
}

ul.venue {
width: 550px;
height: 34px;
list-style: none;
display: block;
background-color: #D1E5FD;
border-style: solid;
border-width: 1px;
border-radius: 2px;
border-color: black;
border-spacing: 5px;
padding-top:1px;
border-radius:5px
}

li.field{
width: 150px;
display: inline-block;
text-align:center;
font-size: 12px;
padding-left: 10px;
background-color: #D1E5FD;
text-decoration: none;
font-family: Tahoma, Geneva, sans-serif;
font-weight: bold;
}

Javascript times.js

window.onload = init;

function init(){
DisplayTimes();
}

function DisplayTimes(){
//legal formats: 1/10-13:00 for date and time
//             : 13:00 for time - presumes utc date is same as local date
var dd = new Date();
var list = document.getElementsByTagName('span');
var mon, date, hr, min;
for (var i=0 ; i<list.length ; i++){
if (list[i].hasAttribute('data-utc')){
var str = list[i].getAttribute('data-utc');
if(str.indexOf('/') < 0){
mon = dd.getMonth()+1;
date = dd.getDate();
hr = str.substring(0,str.indexOf(':'));
}else{
mon = str.substring(0,str.indexOf('/'));
date = str.substring(str.indexOf('/')+1,str.indexOf('-'));
hr = str.substring(str.indexOf('-')+1,str.indexOf(':'));
}

min = str.substring(str.indexOf(':')+1);

dd.setUTCDate(mon);//date of month
dd.setUTCHours(hr); //24hour hour
dd.setUTCMinutes(min); //minutes
dd.setUTCSeconds(0); //seconds

var h = leadzero( dd.getHours() ); 
var m = leadzero( dd.getMinutes() );
var s = leadzero( dd.getSeconds() );

list[i].innerHTML += ' '+ h +':'+ m;
}
}
}

function leadzero(n){
var str1 = n.toString();
if(str1.length < 2){
str1 = '0'+ str1;
}
return str1;
}

JQuery chans2.js

$(".event").click(function(){
   //hide all rrshow
   $(".place").hide();

   //show only required rrshow
   $(this).parent().find(".place").show();
});

спасибо

EDIT: Извините, отправил неправильный код, изменил chan2.js на то, что im использует

  • 0
    Что говорит консоль?

2 ответа

0

У вашего css были проблемы, ваши элементы тела html были помещены вне тегов <body> </body>, и я все изменил для загрузки в пределах одной функции, переданной в $ (document).ready(). В моем браузере работало следующее:

HTML:

<!DOCTYPE html>
<html>
<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>onLoad</title>
    <link href="style2.css" rel="stylesheet" type="text/css"/>


</head>

<body>
<div class="schedule">
    <div class="event">
        <ul class="guides">
            <li class="icon"><img src="" alt="" width="26" height="27" class="icon"/></li>
            <li class="time"><span data-utc="9:05"></span></li>
            <li class="game">Team A vs Team B</li>
        </ul>
    </div>
    <div class="place">
        <ul class="venue">
            <li class="field">Field A</li>
        </ul>
    </div>
</div>
<div class="schedule">
    <div class="event">
        <ul class="guides">
            <li class="icon"><img src="" alt="" width="26" height="27" class="icon"/></li>
            <li class="time"><span data-utc="9:05"></span></li>
            <li class="game">player A vs Player B</li>
        </ul>
    </div>
    <div class="place">
        <ul class="venue">
            <li class="field">Court 3</li>
        </ul>
    </div>
</div>
<div id='out'></div>

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type='text/javascript' src='onLoad.js'></script>
</body>
</html>

JavaScript:

$(document).ready(function () {
    $(".event").click(function () {
        //hide all rrshow
        $(".place").hide();

        //show only required rrshow
        $(this).parent().find(".place").show();
    });

    function DisplayTimes() {
        //legal formats: 1/10-13:00 for date and time
        //             : 13:00 for time - presumes utc date is same as local date
        var dd = new Date();
        var list = document.getElementsByTagName('span');
        var mon, date, hr, min;
        for (var i = 0; i < list.length; i++) {
            if (list[i].hasAttribute('data-utc')) {
                var str = list[i].getAttribute('data-utc');
                if (str.indexOf('/') < 0) {
                    mon = dd.getMonth() + 1;
                    date = dd.getDate();
                    hr = str.substring(0, str.indexOf(':'));
                } else {
                    mon = str.substring(0, str.indexOf('/'));
                    date = str.substring(str.indexOf('/') + 1, str.indexOf('-'));
                    hr = str.substring(str.indexOf('-') + 1, str.indexOf(':'));
                }

                min = str.substring(str.indexOf(':') + 1);

                dd.setUTCDate(mon); //date of month
                dd.setUTCHours(hr); //24hour hour
                dd.setUTCMinutes(+min); //minutes
                dd.setUTCSeconds(0); //seconds

                var h = leadzero(dd.getHours());
                var m = leadzero(dd.getMinutes());
                var s = leadzero(dd.getSeconds());

                list[i].innerHTML += ' ' + h + ':' + m;
            }
        }
    }

    function leadzero(n) {
        var str1 = n.toString();
        if (str1.length < 2) {
            str1 = '0' + str1;
        }
        return str1;
    }

    DisplayTimes();
});

CSS:

@charset "utf-8";
.event {
    width: 600px;
    height: 38px
}

.place{
    display: none;
    width: 590px;
    height: 38px;
    text-align: center;
    font-size: 12px;
    font-weight: bold;
    color: #EB1D2D;
    font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

ul.guides {
    width: 570px;
    height: 34px;
    list-style: none;
    display: block;
    background-color: #D1E5FD;
    border-style: solid;
    border-width: 1px;
    border-color: black;
    border-spacing: 5px;
    padding-top:1px;
    border-radius:5px
}
ul.guides a, ul.guides a:visited, ul.guides a:link {
    display: block;
    text-decoration: none;
    background-color: #8090AB;
    color: black;
}
ul.guides a:hover, ul.guides a:active, ul.guides a:focus {
    background-color: #FFFFFF;
}

li.icon {

    display: inline-block;
    width: 24px;
    height: 24px;
    padding-left: 10px;

}
img.icon{
    display:inline-block;
    padding-top:3px;
}
li.time{
    display:inline-block;
    text-align:center;
    font-size: 12px;
    width: 70px;
    padding-left: 5px;
    color: #0000FF;
    font-family: Tahoma, Geneva, sans-serif;
    font-weight: bold;


}
li.game{
    display: inline-block;
    text-align:center;
    font-size: 12px;
    padding-left: 10px;
    background-color: #D1E5FD;
    text-decoration: none;
    font-family: Tahoma, Geneva, sans-serif;
    font-weight: bold;
}
ul.guides a, ul.nav a:visited{
    display: block;
    text-decoration: none;
    background-color: #8090AB;
    color: #000;
}

ul.guides a:hover, ul.guides a:active, ul.guides a:focus{
    background-color: #6F7D94;
    color: #000;
}

ul.venue {
    width: 550px;
    height: 34px;
    list-style: none;
    display: block;
    background-color: #D1E5FD;
    border-style: solid;
    border-width: 1px;
    border-color: black;
    border-spacing: 5px;
    padding-top:1px;
    border-radius:5px
}

li.field{
    width: 150px;
    display: inline-block;
    text-align:center;
    font-size: 12px;
    padding-left: 10px;
    background-color: #D1E5FD;
    text-decoration: none;
    font-family: Tahoma, Geneva, sans-serif;
    font-weight: bold;
}

FIDDLE

  • 0
    Я вижу, что он работает как nowrap -in <body> и onDomready .. Но тогда как мне ввести код на сайте, чтобы он работал как onDomready или как nowrap - в <body>? Вы увидите, если вы скомпилируете исходный код и запустите сайт, чтобы он не показывал скрытый div и показывал только время
  • 0
    @ user2897821 Я обновил ответ выше, чтобы ответить на твой комментарий выше
Показать ещё 1 комментарий
0

В times.js,
вместо кода

window.onload = init;
function init(){
    DisplayTimes();
}

использование

$(function(){
     DisplayTimes();
}
  • 0
    Извините, я разместил неправильный код для chan2.js .. отредактировал оригинальное сообщение с кодом, который я использую. Я попытался добавить это к chan2.js, но ничего не меняет. также попытался добавить его в time2.js
  • 0
    Как вы сказали, изменил код times2.js. Когда страница загружается в режиме реального времени на сервер, сейчас не работает ни скрытый раздел

Ещё вопросы

Сообщество Overcoder
Наверх
Меню