2017-12-08 8 views
0

저는 StackOverflow 커뮤니티의 멍청한 개발자입니다. javascript/jquery noob입니다. SMS 텍스트 메시지와 유사한 채팅 인터페이스를 구성하려고합니다. 현재 사용자가 텍스트 입력을 할 수 있도록 허용하고 javascript가 지정된 키워드 (예/아니오)를 확인하고 내 HTML에서 특정 숨겨진 div를 표시하여 응답을 시뮬레이션합니다.Javascript/jQuery에 대한 문의/응답, 예/아니요 인터페이스

필자는 꽤 멀리까지 구한 CodePen 예제 (https://codepen.io/adobewordpress/pen/wGGMaV)를 활용하려고 노력해 왔습니다. 그러나 사용자가 여러 개의 질문에 "예"라고 대답하면 Javascript가 첫 번째 예/아니오 응답을 제공하는 사용자로부터 중복/예 응답을 찾고 있습니다.

입력을 받으면 정확한 응답을 제공 한 다음 질문별로 구체적인 사용자 입력 응답을 찾으십시오. 그런 다음 다음 질문으로 이동하십시오. 그러면 다음 응답으로 이동합니다. 사용자. 그들의 대답에 자바 스크립트에서 질문 2 응답을 제공하십시오. 질문 3으로 이동하여 예/아니오 응답을 찾으십시오. 기타

모든 도움을 주시면 감사하겠습니다. 다행히도 멍청한 놈이라 할지라도 나는 도움이되는 대답을 이해하고 일할 수 있습니다.

내 현재 CodePen (https://codepen.io/therise03/pen/bYXVLK)은 위의 논리 설명을 사용하고 있지만 아래에 입력 한대로 내 조건 워크 플로를 사용하고 싶습니다.

원하는 흐름 :

조건 1 [ 질문 : 당신이 당신의 잡지 구독을 계속 하시겠습니까? 텍스트는 계속 계속 또는 NO이 중지 {

If Yes: go to Condition2 
If No: “Thanks you are not subscribed” 

}]

조건 2 [ 질문 : 귀하의 총 $ XXXX.XX 될 것입니다. 파일로 카드로 주문 하시겠습니까? 계속 진행하려면 YES를, 중지하려면 NO를 입력하십시오. {

If Yes: go to Condition3 
If No: “OK we will not use card on file” 

]

조건 3 [ Question3 : 우리는이 주문에 대한 배송 주소를 확인해야합니다. 123 메인 스트리트인가; O'Fallon, MO 63368이 맞습니까? 계속 진행하려면 YES를, 중지하려면 NO를 입력하십시오. {

If Yes: “OK address confirmed” 
If No: “Address not confirmed” 

]

+0

이것은 귀하의 질문에 완전히 대답하지는 못했지만, 저는 이것이 재미있는 운동이고 내 자신의 해결책을 만들었다 고 생각했습니다 : https://codepen.io/anon/pen/VrovoM?editors=1010. 나는 그것이 거의 완전히 다른 코드라는 것을 알고 있지만 그것을 공유 할 것이라고 생각했다. –

+0

와우! 이것은 기본적으로 정확히 내가하려고하는 것입니다! 나는 당신의 코드를 연구하고 그 주위에 내 머리를 감쌀 수 있는지 알아볼 것입니다. 마지막 질문이 하나 있습니다. 질문 3, 예 대답 다음에 "ok 주소 확정"SMS 응답을 보내고 2 초 기다렸다가 예/아니오 응답으로 다른 질문을합니다. 전의. 질문 3 (답변 및 응답 제공) .... 2 초 기다려 .... 질문 4 사용자에게 제시. 이전에 답변을 받으면 함께 모은 코드 펫은 다른 질문 만 쏜다. 이전 질문이 사용자의 응답을 필요로하지 않으면 다른 질문을 강제 할 수 있습니까? –

+0

죄송합니다. 오랫동안 기다리 셨다면 더 명확하게 말씀 드리겠습니다. messageFromThem 응답으로 완료된 주문을 시뮬레이션하고 싶습니다. 그 다음 초 후에 다른 messageFromThem을 시작합니다.하지만 이번에는 이전과 같은 예/아니오 질문으로 시작하십시오. –

답변

0

코멘트에 우리의 대화 후, 나는 대답을 제출 거라고 생각했다.

나는 이것을위한 해결책을 만드는 것이 좋을 것이라고 생각했다. 깨끗하지는 않지만 작동하고 개선 할 수있다.

코드 세트에서 JS 만 변경했습니다.

codepen : codepen.io/anon/pen/POMbNw?

JS :

/* START: HELPERS */ 

function appendFromThem(msg){ // append a "fromThem" msg 
    $('<div class="message"><div class="fromThem"><p>'+msg+'</p></div></div>').insertAfter('.message:last'); 
} 

function appendFromMe(msg){ // append a "myMessage" msg 
    $('form.chat div.messages').append('<div class="message"><div class="myMessage"><p>' + msg + '</p></div></div>'); 
} 

function isString(str){ // check if param is a string 
    return jQuery.type(str) === "string"; 
} 

function areEqual(str1, str2){ // check if strings are the same after trimming and setting to lower case 
    if(!isString(str1) || !isString(str1)) return str1 === str2; // either of them is not a string, use the normal "===" 
    return str1.trim().toLowerCase() === str2.trim().toLowerCase(); 
} 

/* END: HELPERS */ 

// workflow types 
var WF_TYPE = { 
    Q: "question", 
    END: "end", 
    NEW: "new" // start new workflow after cuttent one 
} 

/* 
* The workflow object 
* each sub-object should have a "msg" and responses typically "yes" and "no" 
*/ 
var wf = { 
    type:WF_TYPE.Q, 
    msg:"Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.", 
    continue:{ 
    type: WF_TYPE.Q, 
    msg:"Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.", 
    yes:{ 
     type:WF_TYPE.Q, 
     msg:"We need to confirm your shipping address for this order. Is 123 Main Street; O’Fallon, MO 63368 correct? Text YES to continue or NO to stop.", 
     yes: { 
     endMsg: "OK address confirmed", 
     msg: "some new question?", 
     type : WF_TYPE.NEW, 
     yes:{ 
      msg: "OK cool.", 
      type: WF_TYPE.END 
     }, 
     no:{ 
      msg: "NOT cool...", 
      type: WF_TYPE.END 
     } 

     }, 
     no: { 
     msg:"Address not confirmed", 
     type:WF_TYPE.END 
     } 
    }, 
    no:{ 
     msg: "OK we will not use card on file", 
     type: WF_TYPE.END 
    } 
    }, 
    no:{ 
    msg:"Thanks you are not subscribed", 
    type: WF_TYPE.END 
    } 
} 

/* 
* Transitions current workflow to the next based on user response 
* @param msgFromUser the msg that user typed 
* @returns a response object containing the new workflow, response and other options 
*/ 
function transition(currentWorkflow, msgFromUser){ 
    console.log('getResponse start', currentWorkflow, msgFromUser); 
    if (currentWorkflow.type === WF_TYPE.END){ 
    return { 
     wf: $.extend({}, currentWorkflow) 
    } 
    } 
    else if (currentWorkflow.type === WF_TYPE.Q){ 
    var newWorkflow; 
    var found = false; // if a user reponse was found in current workflow 
    $.each(currentWorkflow, function(key, val){ 
     if(!found && key !== "msg" && areEqual(key, msgFromUser)){ // check if user msg matches any of the valid responses 
     newWorkflow = $.extend({}, val); // cone the value 
     console.log("found it", newWorkflow) 
     found = true; 
     } 
    }); 

    return { 
     wf: newWorkflow ? newWorkflow : $.extend({}, currentWorkflow), 
     errorResponse: found ? undefined : "Sorry, we didn’t understand your response. Please try again." 
    } 
    } 
    else if(currentWorkflow.type === WF_TYPE.NEW){ 
    return { 
     wf: $.extend({}, currentWorkflow) 
    } 
    } 
} 


function scrollDown() { 
    var focusBottom = document.getElementById("textMessage"); 
    focusBottom.scrollTop = focusBottom.scrollHeight; 
} 


$("input").keypress(function(event) { 
    if (event.which == 13) { // if user clicked enter, submit 
    event.preventDefault(); 
    $('form.chat input[type="submit"]').click(); 
    } 
}); 

//appendFromThem(wf.msg); 
$('form.chat input[type="submit"]').click(function(event) { 
    $input = $('form.chat input[type="text"]'); 
    event.preventDefault(); 
    var message = $input.val(); 
    appendFromMe(message); 
    $defered = $.Deferred(); 
    var responseAndWf = transition(wf, message); // get response from workflow 
    if(responseAndWf){ 
    wf = responseAndWf.wf; 
    var response = responseAndWf.errorResponse ? responseAndWf.errorResponse : wf.msg; 
    setTimeout(function() { 
     if(wf.type !== WF_TYPE.NEW){ 
     appendFromThem(response); 
     } 
     scrollDown(); 
     $defered.resolve(); 
    }, 1500); 
    } 

    if(wf.type === WF_TYPE.NEW){ 

    $defered.then(function(){ 
     appendFromThem(wf.endMsg); 
     wf.type = WF_TYPE.Q; 
     setTimeout(function() { 
     appendFromThem(wf.msg); 
     },2000) 
    }); 
    } 
    $input.val(''); 
    scrollDown(); 
}); 

CSS :

input, textarea, [contenteditable] { 
    color: #666; 
    caret-color: blue; 
} 

body { 
    background: #fff; /* For browsers that do not support gradients */ 
    font-family: 'Rubik'; 
    font-weight: 300; 
    color: #fff; 
    font-size:16px; 


} 

h1 { 
    color: #fff; 
    font-family: 'Rubik'; 
    font-weight: 400; 
} 


::-webkit-input-placeholder { /* WebKit, Blink, Edge */ 
color: #cdced2; 
} 
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ 
color: #cdced2; 
opacity: 1; 
} 
::-moz-placeholder { /* Mozilla Firefox 19+ */ 
color: #cdced2; 
opacity: 1; 
} 
:-ms-input-placeholder { /* Internet Explorer 10-11 */ 
color: #cdced2; 
} 
::-ms-input-placeholder { /* Microsoft Edge */ 
color: #cdced2; 
} 
form.chat .myMessage, form.chat .fromThem { 
    max-width: 90%; 
} 



form.chat *{ 
    transition:all .5s; 
    box-sizing:border-box; 
    -webkit-box-sizing:border-box; 
    -moz-box-sizing:border-box; 
} 

form.chat { 
    margin:0; 
    cursor:default; 
    position:absolute; 
    left:0; 
    right:0; 
    bottom:0; 
    top:0; 
    -webkit-touch-callout: none; /* iOS Safari */ 
    -webkit-user-select: none; /* Chrome/Safari/Opera */ 
    -khtml-user-select: none; /* Konqueror */ 
    -moz-user-select: none;  /* Firefox */ 
    -ms-user-select: none;  /* IE/Edge */ 
    user-select: none; 
    border:0 none; 
} 

form.chat span.spinner{ 
    -moz-animation: loading-bar 1s 1; 
    -webkit-animation: loading-bar 1s 1; 
    animation: loading-bar 1s 1; 
    display: block; 
    height: 2px; 
    background-color: #00e34d; 
    transition: width 0.2s; 
    position:absolute; 
    top:0; left:0; right:0; 
    z-index:4 
} 

form.chat .messages{ 
    display:block; 
    overflow-x: hidden; 
    overflow-y: scroll; 
    position:relative; 
    height:90%; 
    width:100%; 
    padding:1% 3% 7% 3%; 
    border:0 none; 

} 

form.chat ::-webkit-scrollbar {width: 3px; height:1px;transition:all .5s;z-index:10;} 
form.chat ::-webkit-scrollbar-track {background-color: white;} 
form.chat ::-webkit-scrollbar-thumb { 
    background-color: #bec4c8; 
    border-radius:3px; 
} 

form.chat .message{ 
    display:block; 
    width:98%; 
    padding:0.5%; 
} 

form.chat .message p{ 
    margin:0; 
} 

form.chat .myMessage, 
form.chat .fromThem { 
    max-width: 50%; 
    word-wrap: break-word; 
    margin-bottom: 20px; 
} 



form.chat .myMessage,.fromThem{ 
    position: relative; 
    padding: 10px 20px; 
    color: white; 
    border-radius: 25px; 
    clear: both; 
    font: 400 15px 'Open Sans', sans-serif; 
} 

form.chat .myMessage { 
    background: #00e34d; 
    color:white; 
    float:right; 
    clear:both; 
    border-bottom-right-radius: 20px 0px\9; 
} 

form.chat .myMessage:before { 
    content: ""; 
    position: absolute; 
    z-index: 1; 
    bottom: -2px; 
    right: -8px; 
    height: 19px; 
    border-right: 20px solid #00e34d; 
    border-bottom-left-radius: 16px 14px; 
    -webkit-transform: translate(0, -2px); 
    transform: translate(0, -2px); 
    border-bottom-left-radius: 15px 0px\9; 
    transform: translate(-1px, -2px)\9; 
} 

form.chat .myMessage:after { 
    content: ""; 
    position: absolute; 
    z-index: 1; 
    bottom: -2px; 
    right: -42px; 
    width: 12px; 
    height: 20px; 
    background: white; 
    border-bottom-left-radius: 10px; 
    -webkit-transform: translate(-30px, -2px); 
    transform: translate(-30px, -2px); 
} 

form.chat .fromThem { 
    background: #E5E5EA; 
    color: black; 
    float: left; 
    clear:both; 
    border-bottom-left-radius: 30px 0px\9; 
} 
form.chat .fromThem:before { 
    content: ""; 
    position: absolute; 
    z-index: 2; 
    bottom: -2px; 
    left: -7px; 
    height: 19px; 
    border-left: 20px solid #E5E5EA; 
    border-bottom-right-radius: 16px 14px; 
    -webkit-transform: translate(0, -2px); 
    transform: translate(0, -2px); 
    border-bottom-right-radius: 15px 0px\9; 
    transform: translate(-1px, -2px)\9; 
} 

form.chat .fromThem:after { 
    content: ""; 
    position: absolute; 
    z-index: 3; 
    bottom: -2px; 
    left: 4px; 
    width: 26px; 
    height: 20px; 
    background: white; 
    border-bottom-right-radius: 10px; 
    -webkit-transform: translate(-30px, -2px); 
    transform: translate(-30px, -2px); 
} 

form.chat date { 
    position:absolute; 
    top: 10px; 
    font-size:14px; 
    white-space:nowrap; 
    vertical-align:middle; 
    color: #8b8b90; 
    opacity: 0; 
    z-index:4; 
} 

form.chat .myMessage date { 
    left: 105%; 
} 

form.chat .fromThem date { 
    right: 105%; 
} 

form.chat input{ 
    /* font: 400 13px 'Open Sans', sans-serif; */ 
    font: 400 1em 'Open Sans', sans-serif; 
    border:0; 
/* padding:0 15px; */ 
    padding: 15px 15px 0 15px; 
    height:10%; 
    outline:0; 
} 

form.chat input[type='text']{ 
    width:73%; 
    float:left; 
} 

form.chat input[type='submit']{ 
    width:23%; 
    background:transparent; 
    color:#00E34D; 
    font-weight:700; 
    text-align:right; 
    float:right; 
} 

    form.chat .myMessage,form.chat .fromThem{ 
    font-size:1.1em; 

    } 



    form.chat .myMessage, 
    form.chat .fromThem { 
    max-width: 90%; 
    } 

@-moz-keyframes loading-bar { 
    0% { 
    width: 0%; 
    } 
    90% { 
    width: 90%; 
    } 
    100% { 
    width: 100%; 
    } 
} 

@-webkit-keyframes loading-bar { 
    0% { 
    width: 0%; 
    } 
    90% { 
    width: 90%; 
    } 
    100% { 
    width: 100%; 
    } 
} 

@keyframes loading-bar { 
    0% { 
    width: 0%; 
    } 
    90% { 
    width: 90%; 
    } 
    100% { 
    width: 100%; 
    } 
} 

/* DEMO */ 
.iphone{ 
    /* 
    width:300px; 
    height:609px; 
    background-image:url('http://www.adobewordpress.com/tasarim/images/iphone6.png'); 
    background-size:100% 100%; 
    margin:0 auto; 
    */ 
    width:100%; 

} 

.border{ 
    /* position:absolute; 
    top:12.3%;right:7%;left:7%;bottom:12%; 
    overflow:hidden; */ 
} 

a.article{ 
    position:fixed; 
    bottom:15px;left:15px; 
    display:table; 
    text-decoration:none; 
    color:white; 
    background-color:#00e34d; 
    padding: 10px 20px; 
    border-radius: 25px; 
    font: 400 15px 'Open Sans', sans-serif; 
} 

HTML :

<div class="iphone"> 
    <div class="imessage-header"></div> 
    <div class="border"> 
    <form class="chat"> 
     <span></span> 
     <div class="messages" id="textMessage"> 
     <div class="message"> 
      <div class="fromThem"> 
      <p>Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.</p> 
      </div> 
     </div> 
     <div class="message magPrice" style="display:none;"> 
      <div class="fromThem new"> 
      <p>Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.</p> 
      </div> 
     </div> 
     <div class="message addressVerification" style="display:none;"> 
      <div class="fromThem new"> 
      <p>We need to confirm your shipping address for this order. Is 123 Main Street; O’Fallon, MO 63368 correct? Text YES to continue or NO to stop.</p> 
      </div> 
     </div> 
     <div class="message goToWeb" style="display:none;"> 
      <div class="fromThem new"> 
       <p>To change your shipping address go to this <a href="#">website</a>.</p> 
      </div> 
     </div> 
     </div> 
     <div style="position:fixed;bottom:0;left:0;border:1px solid #ddd;width:100%;z-index:101;background-color:#fff;height:50px;"> 
     <input type="text" placeholder="Your message" autofocus style="height:auto;"> 
     <input type="submit" value="Send" style="height:auto;"> 
     </div> 
    </form> 
    </div> 
</div> 
편집자 = 여기

0010 codepen 경우의 코드가 더 이상 사용할 수 없습니다입니다

+0

스크립트의 하단에'appendFromThem (wf.msg);'줄 바로 뒤에'scrollDown()'함수를 추가하고 싶었습니다. 각 메시지가 전달 된 후 맨 아래로 스크롤이 시작되었습니다. "주소 확인"을 받으면 몇 초 후에 또 다른 메시지가 표시되어 사용자를 맨 아래쪽으로 유지하지 못합니다. 희망적으로 이것은 의미가 있습니다. –

+0

물론, 기본 질문은 아니지만이 답변은 완벽한 해결책과는 거리가 있지만 질문에 대답합니다 :) –

관련 문제