Inquiry/Response、Yes/No 与 Javascript/jQuery 接口

Inquiry/Response, Yes/No interface with Javascript/jQuery

我是 Whosebug 社区的菜鸟,我们也是 javascript/jquery 菜鸟。我正在尝试构建一个类似于 SMS 文本消息的聊天界面。我目前允许用户输入文本,并让 javascript 查找指定的关键字 (Yes/No) 并在我的 html 中显示特定的隐藏 div 以模拟响应.

我一直在尝试利用一个 CodePen 示例 (https://codepen.io/adobewordpress/pen/wGGMaV),这让我走得很远。但我也在寻找来自用户的重复 Yes/No 回复,如果用户对多个问题说 "Yes",javascript 将提供第一个 Yes/No 回复。

我需要一种方法来包装我的问题并为每个问题寻找特定的用户输入答案,一旦收到输入,提供正确的响应 - 然后转到下一个问题,该问题也会寻找 Yes/No 来自用户的回应。根据他们的回答,然后提供来自 javascript 的问题 2 回复。转到问题 3,查找 Yes/No 响应。等等

非常感谢任何和所有的帮助。希望即使是菜鸟,我也能理解并处理任何有用的回复。

我当前的 CodePen (https://codepen.io/therise03/pen/bYXVLK) 使用上面的逻辑解释,但希望它使用我在下面输入的条件工作流。

所需流量:

条件1 [ 问题:您想继续订阅杂志吗?文本 CONTINUE 继续或 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 [ 问题 3:我们需要确认您此订单的送货地址。是 123 Main Street;奥法伦,MO 63368 正确吗?文本 YES 继续或 NO 停止。 {

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

]

我们在评论中的对话之后,我想我应该提交一个答案。

我认为为此构建一个解决方案对我来说是一个很好的练习,虽然不干净,但它可以工作并且你可以改进它。

我只从你的 codepen 修改了 JS。

codepen: codepen.io/anon/pen/POMbNw?editors=0010

如果 codepen 不再可用,请使用以下代码:

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;
}

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;
  transform: translate(-1px, -2px);
}

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;
}
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;
  transform: translate(-1px, -2px);
}

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>