2015-01-30 3 views
3

JavaScript의 네이티브 함수가 오늘 어떻게 작동하는지 생각 중이므로 alert()을 통해 할 수 있고 createElement()을 사용해야하거나 요소를 만들고 innerHTML을 사용해야한다고 생각했지만 그럴 수 없습니다. 전체 코드를 작성하려면 팝업 요소를 만들고 두 개의 버튼을 만든 다음 원 클릭을 기준으로 true 또는 false을 반환해야합니다.
jowes 상기 :JavaScript에서 confirm()은 어떻게 작동합니까?

일반적 JS 비동기이고; 왜 경보가 특별합니까? 어떻게 그리고 왜 내 자신의 스크립트와 다른 방식으로 UI 요소를 만들 수 있습니까? 여기

내가 알아 낸 코드입니다 :

function confirm(message) { 
    message = message.replace(/"\n"/g, "<br />") 
    createElement(); 
//The create Element is very complicated to create the text box including message. . . 
//These two functions are tied to the button's onclick's. 
    function clickOkay() { 
     valueToReturn = true 
     return true; 
    } 
    function clickCancel() { 
     valueToReturn = true 
     return false; 
    } 
    //here, the user hits the button, and sets valueToReturn 
    return valueToReturn; 
} 

그러나 accessable 한 경우는 백그라운드 스크립트를 중지, 또는의 createElement()가 어떻게 작동하는지 어떻게 이해가 안 돼요, (그러나 대한 질문 이잖아 다른 시간)

+7

'confirm()'은 네이티브 함수입니다. JavaScript로 구현되지 않았습니다. – JJJ

+0

'while (true) {/ * 그러나 이것은 전체 페이지를 응답하지 않게 만들고 스크립트가 종료되도록 요청할 것입니다. * /}'- 접근 관점에서 브라우저의 모든 것 JavaScript는 다음과 같은 콜백을 기반으로해야합니다. "UI를 차단하지 않기". 콜백 (및 HTML 요소 오버레이)이 사용되는 방식에 대한 기존의 "모달 대화 상자"를 살펴보십시오. – user2864740

+3

나는이 질문이 보여주는 직관력을 좋아한다. 보통 JS는 비동기식이다. 왜 '경고'가 특별합니까? 어떻게 그리고 왜 내 자신의 스크립트와 다른 방식으로 UI 요소를 만들 수 있습니까? – joews

답변

5

confirm() -function은 모든 브라우저에서 제공되는 고유 기능입니다. 자바 스크립트를 사용하여 생성되지 않았습니다. 이것은 자기 - 경고 - 상자 구현 될 수

function myConfirm(text, cb){ 
 
    
 
    // We need this later 
 
    var body = document.getElementsByTagName('body')[0]; 
 
     
 
    // First we create a div which holds the alert and give it a class to style it with css 
 
    var overlay = document.createElement('div'); 
 
    overlay.className = 'myConfirm'; 
 
    
 
    // The box holds the content 
 
    var box = document.createElement('div'); 
 
    
 
    var p = document.createElement('p'); 
 
    p.appendChild(document.createTextNode(text)); 
 
    
 
    // We append the text to the div 
 
    box.appendChild(p); 
 
    
 
    // Create yes and no button 
 
    var yesButton = document.createElement('button'); 
 
    var noButton = document.createElement('button'); 
 
    
 
    // Add text and events to the buttons  
 
    yesButton.appendChild(document.createTextNode('Yes')); 
 
    yesButton.addEventListener('click', function(){ cb(true); body.removeChild(overlay); }, false); 
 
    noButton.appendChild(document.createTextNode('No')); 
 
    noButton.addEventListener('click', function(){ cb(false); body.removeChild(overlay); }, false); 
 
    
 
    // Append the buttons to the box 
 
    box.appendChild(yesButton); 
 
    box.appendChild(noButton); 
 

 
    // Append the box to the Overlay 
 
    overlay.appendChild(box) 
 
    
 
    // insert the Overlay with box into the dom  
 
    body.appendChild(overlay); 
 
    
 
} 
 

 
myConfirm('Hello there!', function(value){ console.log(value); });
.myConfirm{ 
 
    position:fixed; 
 
    width:100%; 
 
    height:100%; 
 
    background:rgba(0,0,0,0.05); 
 
} 
 

 
.myConfirm>div{ 
 
    width:200px; 
 
    margin:10% auto; 
 
    padding:10px 20px; 
 
    border:1px solid black; 
 
    background:#ccc; 
 
} 
 

 
.myConfirm div p{ 
 
    text-align:center; 
 
} 
 

 
.myConfirm div button{ 
 
    width:40%; 
 
    margin:0 5%; 
 
}

: 당신이 그 동작을 재현하려는 경우에는이 유사한 길을 갈.
참고 : 기본 경고는 synchronous -function입니다. 즉, 경고 상자가 닫힐 때까지 브라우저가 JavasScript 엔진을 중지합니다. 그 행동을 복제 할 수는 없지만 버튼 중 하나가 클릭 될 때 콜백 함수를 호출 할 수는 있습니다. 이 경우 콜백은 값을 콘솔에 기록합니다.

희망은 여기 있습니다! 자바 스크립트는 새로운 때
위로 일 업데이트 된 질문에

UPDATEconfirm 특정 값을 사용자에게 유효한 방법이었다. confirm, promptalert은 요즘의 특수 기능으로, JavaScript- "흐름"을 깨기 때문에 정상적인 기능과 완전히 다른 기능을합니다. 이유를 물었을 때 : 요즘 어쩌면 좋은 기능 이었을지 모릅니다. 이전 버전의 alert은 시스템 메시지처럼 보였습니다 (IE에서는 여전히 그렇습니다). 적어도 Firefox에서는 경고가 호출 되더라도 요즘 브라우저와 정상적으로 상호 작용할 수 있습니다.
이것이 단지 오늘날 디버깅에만 사용되는 이유입니다 (여기에서도 심지어 console.log이 더 나은 선택입니다).

오늘 (FF로) 경고 메시지가 browser-intern html과 CSS로 렌더링되었음을 확신합니다.

9

alert, confirmprompt은 모두 브라우저에서 구현되는 DOM API입니다. 개발자는 DOM 요소를 만들어 DOM 요소를 만들지 않으며 JavaScript 엔진이 사용자가 단추 중 하나를 클릭 할 때까지 기다릴 수 없으므로 해당 기능을 JavaScript로 정확하게 다시 만들 수 없습니다. 당신이 만든 대화 상자의 결과를 포함 할 콜백을 요구함으로써 만 접근 할 수 있습니다.

function customConfirm(message, callback) { 
    message = message.replace(/"\n"/g, "<br />") 
    createElement(); 
    //The create Element is very complicated to create the text box including message. . . 
    function clickOkay() { 
     callback(true); 
    } 
    function clickCancel() { 
     callback(false); 
    } 
} 
customConfirm("Hello World!", function (result) { 
    console.log(result); 
}); 
+2

물론 두 개의 클릭 기능을 버튼의 클릭 이벤트에 연결해야합니다. –

+0

두 번의 클릭 기능을 버튼의 클릭 이벤트에 묶는 예제를 추가 할 수 있습니까? – SCGB

+1

@SamC 그 주석의 문맥을 기억하지 못합니다. 약간의 마음 확장? –

관련 문제