Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Проблема с IE (https://javascript.ru/forum/misc/36524-problema-s-ie.html)

Vasy 18.03.2013 13:50

Проблема с IE
 
Добрый день.Вот просто решил попробовать открыть этот код в IE и опупел мягко говоря от результата...Все
<div></div>
создаютса не так как я создавал.Подключение xml файла как-бы происходит но везде где подключаетса в коде xml выводитса udentified.Что с этим можно поделать?Вообще я посидел почитал на выходных об подобных проблемах,и понял что так сказать целая наука что бы все поддерживалось в любом браузере?Почитал про кросс-браузерность несовсем допер в чем же беда,ну вернее в чем беда я понял что IE что-то неподдерживает из кода а что именно незнаю.Подскажите пожалуста где можно почитать про такие проблемы и как с ними боротса?

xml'ка
<?xml version="1.0" encoding="windows-1251"?>
<?xml-stylesheet href="style.css" type="text/css"?>
<!DOCTYPE test SYSTEM "test.xml">
<test>
<style  border="5px solid black" hight="350px"  width="350px"  padding="20px" margin="20px" position="relative" ></style>
<buttonstyle hight="40px" width="50px" position="fixed" marginleft="150px" ></buttonstyle>
	<attemptsanswer>1</attemptsanswer>
	<questions>
		
		<question>Вопрос</question>
		<answer rating="1"> </answer>
		<answer rating="0"> </answer>
	
		<question1>Вопрос1</question1>
		<answer rating="0"> </answer>
		<answer rating="1"> </answer>
		<textanswer>Да</textanswer>
		<textanswer>Нет</textanswer>
	</questions>
		
	
<TextButton>Ответить на вопрос</TextButton>
<TextButton>Стереть ответы</TextButton>
<TextButton>начать тест заново</TextButton>
<ResultTextTrue>Ваш ответ верен!</ResultTextTrue>
<ResultTextFalse>Ваш ответ не верен!</ResultTextFalse>
</test>


JavaScript
<!DOCTYPE html>
<html>

<head>



<meta charset="utf-8" />
	<title>Test</title>
	
<script type="text/javascript" src="jquery.js"></script>
	<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">

							
var answer={}

		$(document).ready(function(){
			$.ajax({
				type: "GET",  
				url: "test.xml", 
				dataType: "xml", 
				success: vasa	
	 			
		});
		
	
		var button2 = document.getElementById("id1");
		button2.style.display='none';
		function vasa(xml) { 
				attemptsanswer=$(xml).find('attemptsanswer')[0].textContent; 
					
				 textanswer=$(xml).find('textanswer  ')[0].textContent;
				$('.cont2').append(''+textanswer+'');
				
				
				 textanswer=$(xml).find('textanswer')[1].textContent;
				$('.cont2').append(''+textanswer+'');
		        question=$(xml).find('question')[0].textContent;
				$('.cont1').append('<p><label><h4>'+question+'</h4></label></p>');
				question1=$(xml).find('question1')[0].textContent;
				$('.bond1').append('<p><label><h4>'+question1+'</h4></label></p>');
				TextButton=$(xml).find('TextButton')[0].textContent;
				$('.onki').append('<p><label><h4>'+TextButton+'</h4></label></p>');
				TextButton=$(xml).find('TextButton')[1].textContent;
				$('.lolki').append('<p><label><h4>'+TextButton+'</h4></label></p>');
				TextButton=$(xml).find('TextButton')[2].textContent;
				$('.lolki1').append('<p><label><h4>'+TextButton+'</h4></label></p>');
				ResultTextTrue=$(xml).find('ResultTextTrue')[0].textContent;
				
				ResultTextFalse=$(xml).find('ResultTextFalse')[0].textContent;

				
				var answers = $(xml).find('answer');
				
 
             		        answers.each(function(index){
									
                                var a = this.textContent;
								
								
                                var rating = +this.getAttribute('rating');
								
									var inputs = document.getElementsByTagName('input');
										if(inputs.length<2)
											{	
											
                                $('.cont').append('<input   name="group1"  type="radio">');
								
								            }
											else
											{
								$('.bond').append('<input   name="group2"  type="radio">');
										   }
                                answer[index] = rating;

				

				
 
                });
				
				
				
				
			
				var div = document.getElementById('id')
				var decoration = xml.querySelector('style');
				div.style.border = decoration.getAttribute('border');
				div.style.width = decoration.getAttribute('width'); 
				div.style.height = decoration.getAttribute('hight');
				div.style.padding = decoration.getAttribute('padding');
				//div.style.margin = decoration.getAttribute('margin');
				div.style.position = decoration.getAttribute('position');
				
				
			//	var p = document.getElementById('id1')
			//	var decoration = xml.querySelector('buttonstyle');
			//	p.style.position = decoration.getAttribute('position');
			//	p.style.width = decoration.getAttribute('width'); 
			//	p.style.height = decoration.getAttribute('hight');
			//	p.style.margin-left = decoration.getAttribute('marginleft');
			//	p.style.margin = decoration.getAttribute('margin');

		}
	
				
	 			
		});
		
		
			
				
	 			
		
			

												
var pressed=0;
					
function checkAnswer() {
var error = false;
			
					   
            var inputs = document.getElementsByTagName('input');
            for(var i = 0; i < inputs.length ; i++){
               var checked = inputs[i].checked;
              var right = answer[i] == 1;			 			 
               if (checked !== right){
               error=true;
               break;
			   
               }
        }
							
							
					if(pressed<attemptsanswer)
							{
					
					  i = ++pressed;
								
				
                       }
					   else
					   {		
							alert("Вы исчерпали количество попыток")
							pressed=0;
			


							var button = document.getElementById("button");
							button.style.display='none';
							var button1 = document.getElementById("id2");
							button1.style.display='none';
							var button2 = document.getElementById("id1");
							button2.style.display='';
							button2.onclick = function(event){							
							button.style.display='';
							button1.style.display='';
							button2.style.display='none';
							output.value='Пройдите тест ище раз'
							}
						
							
					   }
        output.value=error ? ''+ResultTextFalse+'' : ''+ResultTextTrue+'';
		
        return false;
							
		
		
    }
	
	
       
      
       
   

</script>

</head>
<body>


<form  onsubmit="return checkAnswer()">
	
	 
	 
<tr>
<td>
	 <div id="id">	 
	 
	 <div  class='cont2' style="margin-left:156px"></div>
	 
	 
	 <hr>
	
	 <div  class='cont1' ></div>
	

	 <div align="center"   class='cont' ></div>
	
	 <hr> 
	 <div class="bond1"></div>
	 <div align="center" class='bond'></div>
	 <hr>
	
	</div>
	</td>
	<td>
	<p style="position:relative"><button id="button" type="submit"  ><div  class='onki'></div></button> <button id="id2" type="reset"><div class='lolki'></div></button><button id="id1" type="reset"><div class='lolki1'></div></button></p>

    <p style=" position:relative"><textarea id="output" readonly></textarea></p>
	</td>
</tr>	

	
	 
    

</form>



</body>

</html>

Vasy 18.03.2013 14:01

Пока единственное что нашол это то что в IE нету TextContent а есть innerText и то после исправления это проблему не решило.А только ухудшило.
А и непомню где но гдето вычитал что если парсить xml через ajax в IE это ни как незаработает а что бы работало и в IE нужно использовать json.Скажите это правда?Если да мне нужно ереписывать почти весь код по новой?

И да если это критично то пользуюсь wamp server.Так как нашол что ище может зависить от этого,хотя почитав посты людей и я понял что у меня собственно уже все соблюдено

danik.js 18.03.2013 18:31

Цитата:

Сообщение от Vasy
если парсить xml через ajax в IE это ни как незаработает

Это не так. Все работает даже в IE6 (через ActiveX).
Цитата:

Сообщение от Vasy
в IE нету TextContent а есть innerText

В старых IE в xml-нодах нету ни того, ни другого. Можно получить содержимое другим способом(вроде кроссбраузерно): node.firstChild.nodeValue (поясню: внутри ноды-элемента текстовое содержимое представляет из себя текстовую ноду, node.firstChild как раз ссылается на нее, и у текстовых нод содержимое доступно через nodeValue)

Vasy 18.03.2013 18:35

danik.js,
А можно часть кода?ну получение хоть чего-то того что сейчас я получаю не кроссбраузерно?Я не совсем понимаю куда это применить.

danik.js 18.03.2013 19:02

Гы, а я и забыл про jquery )
в jquery весь код уже написали за тебя, поэтому xml должен работать.
Единственное, вместо [0].textContent пиши .text()

Vasy 18.03.2013 19:07

спасибо.Тогда если вот так то в IE текст отображаетса а разбивка страници которую я тоже подключаю из xml и сама логика что будет происходить при нажатии на кнопку работает не коректно.
Ну тоесть не создаётса эта рамка,и логика обработки правильности ответов не работает.И ище один прикол,создаётса только одна кнопка в которой текс всех трех,и я непойму почему?Ведь я вызываю разные класы для трех разных кнопок
Делаю это вот так

attemptsanswer=$(xml).find('attemptsanswer').text(); 
					
				 textanswer=$(xml).find('textanswer  ').text();
				$('.cont2').append(''+textanswer+'');
				
				
				 textanswer1=$(xml).find('textanswer1').text();
				$('.cont2').append(''+textanswer1+'');
		        question=$(xml).find('question').text();
				$('.cont1').append('<p><label><h4>'+question+'</h4></label></p>');
				question1=$(xml).find('question1').text();
				$('.bond1').append('<p><label><h4>'+question1+'</h4></label></p>');
				TextButton=$(xml).find('TextButton').text();
				$('.onki').append('<p><label><h4>'+TextButton+'</h4></label></p>');
				TextButton1=$(xml).find('TextButton1').text();
				$('.lolki').append('<p><label><h4>'+TextButton1+'</h4></label></p>');
				TextButton2=$(xml).find('TextButton2').text();
				$('.lolki1').append('<p><label><h4>'+TextButton2+'</h4></label></p>');
				ResultTextTrue=$(xml).find('ResultTextTrue').text();
				
				ResultTextFalse=$(xml).find('ResultTextFalse').text();

Vasy 18.03.2013 19:24

а вообще я немогу понять почему оно не работает,ведь все подключения из xml делаютса с помощью alax jquery а IE поддерживает их полностью.

Vasy 19.03.2013 14:20

Ну и я смог решить только проблему с кнопками,теперь кнопки создаютса нормально как нужно.А весь фукционал не работает.
Неработае подключение стилей вот этих
var div = document.getElementById('id')
				var decoration = xml.querySelector('style');
				div.style.border = decoration.getAttribute('border');
				div.style.width = decoration.getAttribute('width'); 
				div.style.height = decoration.getAttribute('hight');
				div.style.padding = decoration.getAttribute('padding');
				div.style.margin = decoration.getAttribute('margin');
				div.style.position = decoration.getAttribute('position');

и неработает проверка ответов на правильность и вывод в текстовое поле.

что с этим можно поделать?подскажите пожалуста

danik.js 19.03.2013 16:37

querySelector не работает в IE7. Возможно в IE8 нет этого метода у xml-узлов.

Vasy 19.03.2013 16:40

крутяк буду знать,а как это можно исправить?Ну что есть в IE?
Да и пробивал почти все методы и свойства на совместимость вот что пишут про querySelector

Если говорить о совместимости с браузерами, то querySelector() поддерживаются в IE8+ (только в стандартном режиме IE8)
а я пытаюсь открывать в IE9,и поидее все должно работать(

и почему вот это
function checkAnswer() {
var error = false;
			
					   
            var inputs = document.getElementsByTagName('input');
            for(var i = 0; i < inputs.length ; i++){
               var checked = inputs[i].checked;
              var right = answer[i] == 1;			 			 
               if (checked !== right){
               error=true;
               break;
			   
               }
        }
							
						
					if(pressed<attemptsanswer)
							{
					
					  i = ++pressed;
								
				
                       }
					   else
					   {		
					    
							alert("Вы исчерпали количество попыток")
							pressed=0;
							var button = document.getElementById("button");
							button.style.display='none';
							var button1 = document.getElementById("id2");
							button1.style.display='none';
							var button2 = document.getElementById("id1");
							button2.style.display='';
							button2.onclick = function(event){	
							
							
							
							button.style.display='';
							button1.style.display='';
							button2.style.display='none';
							output.value='Пройдите тест ище раз'
						
						
							
											g=++pressed1;
											
											alert(pressed1);
											if(pressed1>attemptsanswer)
											{
											button.style.display='none';
											button1.style.display='none';
											button2.style.display='none';
											var button3 = document.getElementById("id3");
											button3.style.display='';
											
											}
										
										
							
						
							}
			
							
					   }
					
        output.value=error ? ''+ResultTextFalse+'' : ''+ResultTextTrue+'';
		
        return false;
					
		
    }

тоже не работает?

danik.js 19.03.2013 17:14

Цитата:

Сообщение от Vasy
и почему вот это тоже не работает?

И что, консоль молчит?

Vasy 19.03.2013 17:16

Цитата:

Сообщение от danik.js (Сообщение 241523)
И что, консоль молчит?

Ну да он ругаетса на querySelector
А чем его можно заменить в таком случае?

И вообще почему он на него ругаетса?

Vasy 19.03.2013 18:09

со стилями проблему решыл просто явно ему задавал вот так
var div = document.getElementById('id')
				//var decoration = xml.querySelector('style');
				div.style.border = $(xml).find('style').attr('border');
				div.style.width = $(xml).find('style').attr('width'); 
				div.style.height = $(xml).find('style').attr('hight');
				div.style.padding = $(xml).find('style').attr('padding');
				div.style.margin = $(xml).find('style').attr('margin');
				div.style.position = $(xml).find('style').attr('position');

Теперь рамку рисует отлично.Все работает почти коректо осталось исправить какието мелочи.

Вообще я в шоке,насколько IE "тупой". Чтобы IE работал корректно ему всегда нужно все задавать явно?.Тоесть вот так он нехотел работать
output.value=error ? ''+ResultTextFalse+'' : ''+ResultTextTrue+'';

а так работает коректно
var c=document.getElementById('output');
        c.value=error ? ''+ResultTextFalse+'' : ''+ResultTextTrue+'';


И да у меня ище такой вопрос,почему стоит
<meta  charset="utf8" />

а вот здесь
var b=document.getElementById('output');	
							b.value='Пройдите тест ище раз'

выводит иероглифы?
Он же вроде должен читать все символы по русски,или нет?ну вернее в хроме мозиле сафари и т.п. браузерах все норм а IE ругаетса,может ище что-то помимо
<meta  charset="utf8" />
нужно написать ?

Ну а вообще спасибо за помощь огромное

danik.js 19.03.2013 18:55

utf-8 вроде должно быть, а не utf8. К тому же сервер может выставить другую кодировку в заголовке Content-Type, ей отдается предпочтение.

Vasy 19.03.2013 19:04

danik.js,
Спасибо вам за некие пояснение=)

Если вдруг у кого будут похожые проблемы то решил их так
<html>

<head>



<meta  charset="utf-8" />
	<title>Test</title>
	
<script type="text/javascript" src="jquery.js"></script>
	<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">

						
var answer={}

		$(document).ready(function(){
			$.ajax({
				type: "GET",  
				url: "test.xml", 
				dataType: "xml", 
				success: vasa	
	 			
		});
		
		
		var button2 = document.getElementById("id1");
		button2.style.display='none';
		var button3 = document.getElementById("id3");
		button3.style.display='none';
		
		function vasa(xml) { 
				attemptsanswer=$(xml).find('attemptsanswer').text(); 
				attemptext=$(xml).find('attemptext').text(); 
				attemptext1=$(xml).find('attemptext1').text(); 
					
				 textanswer=$(xml).find('textanswer  ').text();
				$('.cont2').append(''+textanswer+'');
				
				
				 textanswer1=$(xml).find('textanswer1').text();
				$('.cont2').append(''+textanswer1+'');
		        question=$(xml).find('question').text();
				$('.cont1').append('<p><label><h4>'+question+'</h4></label></p>');
				question1=$(xml).find('question1').text();
				$('.bond1').append('<p><label><h4>'+question1+'</h4></label></p>');
				TextButton=$(xml).find('TextButton').text();
				$('.onki').append('<p><label><h4>'+TextButton+'</h4></label></p>');
				TextButton1=$(xml).find('TextButton1').text();
				$('.lolki').append('<p><label><h4>'+TextButton1+'</h4></label></p>');
				TextButton2=$(xml).find('TextButton2').text();
				$('.lolki1').append('<p><label><h4>'+TextButton2+'</h4></label></p>');
				TextButton3=$(xml).find('TextButton3').text();
				$('.lolki2').append('<p><label><h4>'+TextButton3+'</h4></label></p>');
				ResultTextTrue=$(xml).find('ResultTextTrue').text();
				
				ResultTextFalse=$(xml).find('ResultTextFalse').text();
				
	answer1=$(xml).find('answer').text();
	
	
				var answers = $(xml).find('answer');
				
 
             		        answers.each(function(index){
									
                                var a = this.textContent;
								
								
                                var rating = +this.getAttribute('rating');
								
									var inputs = document.getElementsByTagName('input');
										if(inputs.length<2)
											{	
											
                                $('.cont').append('<input   name="group1"  type="radio">');
								
								            }
											else
											{
								$('.bond').append('<input   name="group2"  type="radio">');
										   }
                                answer[index] = rating;

				

				
 
                });
				
				
				
				
			
				var div = document.getElementById('id')
				//var decoration = xml.querySelector('style');
				div.style.border = $(xml).find('style').attr('border');
				div.style.width = $(xml).find('style').attr('width'); 
				div.style.height = $(xml).find('style').attr('hight');
				div.style.padding = $(xml).find('style').attr('padding');
				div.style.margin = $(xml).find('style').attr('margin');
				div.style.position = $(xml).find('style').attr('position');
				
				
			//	var p = document.getElementById('id1')
			//	var decoration = xml.querySelector('buttonstyle');
			//	p.style.position = decoration.getAttribute('position');
			//	p.style.width = decoration.getAttribute('width'); 
			//	p.style.height = decoration.getAttribute('hight');
			//	p.style.margin-left = decoration.getAttribute('marginleft');
			//	p.style.margin = decoration.getAttribute('margin');

		}
	
				
	 			
		});
		
		
			
				
	 			
		
			


var pressed=0;
var pressed1=0;		
function TrueAnswer(){
  
	  var inputs1 = document.getElementsByTagName('input');
            for(var k = 0; k < inputs1.length ; k++){
               
				if(answer[k] == 1){
				
				
				
				error=true;
            
               
               break;
			   
               }
        }	 
var n=document.getElementById('output');			
         n.value='бла бла бла';
	}			
function checkAnswer() {
var error = false;
			
					   
            var inputs = document.getElementsByTagName('input');
            for(var i = 0; i < inputs.length ; i++){
               var checked = inputs[i].checked;
              var right = answer[i] == 1;			 			 
               if (checked !== right){
               error=true;
               break;
			   
               }
        }
							
						
					if(pressed<attemptsanswer)
							{
					
					  i = ++pressed;
								
				
                       }
					   else
					   {		
					    
							
							pressed=0;
							var button = document.getElementById("button");
							button.style.display='none';
							var button1 = document.getElementById("id2");
							button1.style.display='none';
							var button2 = document.getElementById("id1");
							button2.style.display='';
							button2.onclick = function(event){	
							
							
							
							button.style.display='';
							button1.style.display='';
							button2.style.display='none';
						
						
						
							
											g=++pressed1;
											
											
											if(pressed1>attemptsanswer)
											{
											button.style.display='none';
											button1.style.display='none';
											button2.style.display='none';
											var button3 = document.getElementById("id3");
											button3.style.display='';
											alert('ваши попытки закончились.Узнайте правильный ответ');
											}
										
										
							
						
							}
			
							
					   }
		var c=document.getElementById('output');			
        c.value=error ? ''+ResultTextFalse+'' : ''+ResultTextTrue+'';
		
        return false;
					
		
    }
	
	
       
      
       
   

</script>

</head>
<body>


<form  onsubmit="return checkAnswer()">
	
	 
	 

	 <div id="id">	 
	 
	 <div  class='cont2' style="margin-left:156px"></div>
	 
	 
	 <hr>
	
	 <div  class='cont1' ></div>
	

	 <div align="center"   class='cont' ></div>
	
	 <hr> 
	 <div class="bond1"></div>
	 <div align="center" class='bond'></div>
	 <hr>
	
	</div>


	<p style="position:relative"><button id="button" type="submit"  ><div  class='onki'></div></button> <button id="id2" type="reset"><div class='lolki'></div></button><button id="id1" type="reset"><div class='lolki1'></div></button><button id="id3" type="button" onclick="TrueAnswer()" ><div  class='lolki2'></div></button></p>

    <p style=" position:relative"><textarea id="output" readonly></textarea></p>
	
	

	
	 
    

</form>



</body>

</html>

danik.js 19.03.2013 19:09

Цитата:

Сообщение от Vasy
c.value=error ? ''+ResultTextFalse+'' : ''+ResultTextTrue+'';

Зачем тут плюсуются пустые строки?

Vasy 20.03.2013 04:21

дабы выводился текст из xml файла(подругому неполучилось выводить)

danik.js 20.03.2013 06:55

То есть так не работает?
c.value= error ? ResultTextFalse : ResultTextTrue;


Часовой пояс GMT +3, время: 23:57.