如何使jQuery事件函数同步?

时间:2019-05-09 03:03:38

标签: jquery async-await

我希望从<select><input>标记中获取值以进行进一步处理,但是由于JS本质上是异步的,因此它不等待取回值,而无需等待就可以进行下一步。这是我的代码:

$(".button").click(function(){
    $("select.form-control").change(function(){
        invoiceType=$(this).children("option:selected").val();
    });

    $("input").blur(function(){
        invoiceNumber=$(this).val();
    });

    if(invoiceNumber && invoiceType){ // here I am getting undefined
      //logic
    }
}

我尝试过的事情:

1)异步/等待

2)Jquery.when()。then() 但是没有运气。感谢帮助。

2 个答案:

答案 0 :(得分:1)

您可以用非常简单的方法解决它。只需在两个事件处理程序中都调用一个函数,然后在定义了两个变量的情况下执行逻辑即可。

<?php 
$soap_response = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header />
   <soapenv:Body>
      <unirec:HotelCreateReservationReq xmlns:unirec="http://www.travelport.com/schema/universal_v41_0" xmlns:com="http://www.travelport.com/schema/common_v41_0" xmlns:hot="http://www.travelport.com/schema/hotel_v41_0" AuthorizedBy="user" ProviderCode="1V" TraceId="trace" UserAcceptance="true" TargetBranch="P3029488">
         <com:BillingPointOfSaleInfo OriginApplication="uAPI" />
         <com:BookingTraveler>
            <com:BookingTravelerName First="Charlie" Last="Davidson" />
            <com:PhoneNumber Number="3343720641" />
            <com:Email EmailID="Cdtigger82@hotmail.com" />
            <com:Address>
               <com:Street>111 Regency Court</com:Street>
               <com:City>Warner Robins</com:City>
               <com:PostalCode>31088</com:PostalCode>
               <com:Country>US</com:Country>
            </com:Address>
         </com:BookingTraveler>
         <hot:HotelRateDetail RatePlanType="KEN013A" />
         <hot:HotelProperty HotelChain="HI" HotelCode="14993" />
         <hot:HotelStay>
            <hot:CheckinDate>2019-04-27</hot:CheckinDate>
            <hot:CheckoutDate>2019-04-28</hot:CheckoutDate>
         </hot:HotelStay>
         <hot:HotelSpecialRequest />
         <com:PointOfSale ProviderCode="1V" PseudoCityCode="2GM4" IATA="34651842" />
         <hot:GuestInformation NumberOfRooms="1" />
      </unirec:HotelCreateReservationReq>
   </soapenv:Body>
</soapenv:Envelope>
XML;


//your php code here to read any data from the response

// $xmlres = htmlentities($soap_response);

$fileContents = str_replace(array("\n", "\r", "\t"), '', $soap_response);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);

$xml = simplexml_load_string($soap_response);
foreach($xml->hot[0]->attributes() as $attr => $val) {
   echo $attr,'="',$val,"\"\n";
}

答案 1 :(得分:0)

您应该小心在click处理程序中注册这些事件。如果不取消注册,事情可能会很快变得混乱。

您需要某种状态来跟踪事物,因此我创建了eventFlags

let button = document.querySelector('button');
let select = document.querySelector('select');
let input = document.querySelector('input');

let eventFlags = {
  clicked: false,
  changed: false,
  blurred: false
};

button.onclick = function() {
  console.log('clicked');
  eventFlags.clicked = true;
  return false;
};

select.onchange = function(event) {
  console.log('changed');
  eventFlags.changed = event.target.value;
  doCheck();
};

input.onblur = function(event) {
  console.log('blurred');
  eventFlags.blurred = event.target.value;
  doCheck();
};

function doCheck() {
  if (eventFlags.clicked &&
    eventFlags.changed &&
    eventFlags.blurred) {
    alert(`ready: ${eventFlags.changed} ${eventFlags.blurred}`);
  }
}
<form>
  <tbody>
    <tr>
      <td>button</td>
      <td>
        <button>click</button>
      </td>
    </tr>
    <tr>
      <td>select</td>
      <td>
        <select>
          <option value="a">A</option>
          <option value="b">B</option>
        </select>
      </td>
    </tr>
    <tr>
      <td>input</td>
      <td><input type="text"></td>
    </tr>
  </tbody>
</form>