2016-09-17 7 views
-2

을 제공 I 다음 코드 (더미)이 있습니다 param1이있는 경우 어떻게해야 무엇JS - document.querySelector() || document.querySelector는() 타입 에러

myFunction(document.querySelector('[data-param="param1"]').textContent || document.querySelector('[data-param="param2"]').textContent); 

가있다 하나는, 다른, falsy의 사용을 이용하여 param2를 사용하는 것이 사용 . 나는 이것을 사용하는 것이 최선이 아니라는 것을 알고 있지만 (here 참조), 내 상황에 대해 생각해 냈습니다.

이것을 설명하기 위해 jsfiddle을 만들려고했습니다. 그러나 이것은 두 개의 다른 브라우저 (묻지 않음)를 사용하고 있기 때문에 콘솔에서 다른 표현 일 수는 있지만 오류는 잘못되었습니다.

TypeError: document.querySelector(...) is null

와 크롬에서 말한다 :

화재에서

버그는 말한다

TypeError: Cannot read property 'your-property-here' of null

내가 나는 그것이 document.getElementById('param1') || document.getElementById('param2') 작업을했다고 생각하지만, 무엇 jsfiddle가주고 것은하지 않는 것 querySelector 또는 getElementById에서 작업하십시오.

이이 기능이나 버그가 ...

은 내가 docs에 이것에 대해 아무것도 찾을 수 없습니다

, 내 구글은 아무것도 찾지 못했습니다 검색 하시나요? querySelector (또는 getElementById1 등)에 falsy 값을 악용 할 수있는 이벤트가 있습니까? 내가하고 싶은 일을하는 가장 좋은 방법은 무엇일까요?

+0

귀하의 피들에있는 코드는 매우 다릅니다 : 'document.querySelector (something)'속성을 사용하고 있습니다.물론 요소가 없을 때는 작동하지 않습니다. –

+0

@ DenysSéguret는 주저하며, 그것을 고쳤습니다. – 4lackof

답변

2

오류가 나타나는 이유는 첫 번째 쿼리가 null을 반환하고 속성 데이터 집합이 없기 때문입니다. 대신이 시도 : document.querySelector('[data-example="example1"]')가 null 반환하는 경우

(document.querySelector('[data-example="example1"]') || document.querySelector('[data-example="example2"]')).dataset.example

자, 대신 document.querySelector('[data-example="example2"]')을 다할 것입니다. 두 쿼리가 모두 null을 반환하면 오류가 계속 발생한다는 것을 알고 있어야합니다.

0

귀하의 사례와 관련하여 javascript에는 버그가 없습니다. 코드의 버그입니다. 제공된 매개 변수가 document의 요소와 일치하지 않는 경우 document.querySelector() 또는 getElementByIdnull을 반환하기 때문에 따라서 null.anything은 오류를 발생시킵니다. id1 또는 id2 모두 다음과 같은 오류가 발생 될 수 아무것도 일치하지 않는 경우 당신은 또한 아래의 이러한 오류를 피하기 위해 같은 여기

var res = (document.getElementById('id1') || document.getElementById('id2')).id; 

그리고 당신의 코드를 다시 작성할 수 있습니다. 당신은 일치가없는 경우 다음 resundefined이 될 것입니다,이 경우 지금,

var res = (document.getElementById('id1') || document.getElementById('id2') || {}).id; 

을 또한 상황을 처리 아래와 같이 할 수 있습니다.

0

다음과 같이 코드를 수정해야 할 수도 있습니다.

// data attribute: 
var elm1 = document.querySelector('[data-example="example1"]') || document.querySelector('[data-example="example2"]'); 
    elm2 = document.getElementById('id1') || document.getElementById('id2'); 
document.getElementsByTagName('BUTTON')[0].addEventListener('click', function(e) { 
    try { 

    e.target.className += elm1.dataset.example; 
    } catch(e) { 
    document.getElementById('log').innerHTML += '<div>' + e + new Date() + '</div>'; 
    } 
}); 

// id: 
document.getElementsByTagName('BUTTON')[1].addEventListener('click', function(e) { 
    try { 
    e.target.className += elm2.id 
    } catch(e) { 
    document.getElementById('log').innerHTML += '<div>' + e + new Date() + '</div>'; 
    } 
});