简体   繁体   English

在jquery Submit函数内分配全局变量并传递给regex函数

[英]Assign global variable inside jquery submit function and pass to regex function

Assign value to global tracking variable on submit of form. 在提交表单时向全局跟踪变量分配值。

var tracking;

$('.form-inline').submit(function (e) {
  e.preventDefault();
  tracking = jQuery('input[name="tracking"]').val();
  init()
})

execute function init() 执行函数init()

function init() {
  Tabletop.init({
    key: public_spreadsheet_url,
    callback: showInfo,
    simpleSheet: true
  })
}

Which initiates the showInfo callback 哪个启动showInfo回调

var zipMatches = "";
function showInfo(data, tabletop) {
  alert('Callback initiated..');
  for (var i = 0; i < data.length; i++) {
    var myRegex = '/' + tracking + '/';
    console.log(myRegex)
    if (myRegex.test(data[i].tracking)) {
      zipMatches = zipMatches + data[i].location_1 + ", " + data[i].location_2 + ", " + data[i].location_3;
    }
  }
  //write it into the DOM 
  var myElement = document.querySelector(".myJSON");
  myElement.innerHTML = "<h3>List of Zipcodes that match tracking ID: </h3><p>" + zipMatches + "</p>";
}

myRegex.test is not a function myRegex.test不是函数

However regex function works with hardcoded value 但是正则表达式功能可以使用硬编码值

if (/ABCD123/.test(data[i].tracking)) {...

How do I pass the regex value as a global variable? 如何将正则表达式值作为全局变量传递?

.. ..

Edit (working callback function): 编辑(工作回调函数):

function showInfo(data, tabletop) {
  var regexp = new RegExp(tracking);
  for (var i = 0; i < data.length; i++) {
    if (regexp.test(data[i].tracking)) {
      zipMatches = zipMatches + data[i].location_1 + ", " + data[i].location_2 + ", " + data[i].location_3;
    }
  }.. 

Plese try with following sol: 请尝试以下溶胶:

var regexp = new RegExp(tracking);

and please put it outside of forloop. 并将其放在forloop之外。 So it is optimized. 因此它是优化的。

Since you have tried var regexp = "/" + tracking + "/"; 由于您已经尝试过var regexp = "/" + tracking + "/"; will convert it into string. 将其转换为字符串。 Not regex object. 不是正则表达式对象。 So you won't get test method in it. 因此,您将无法获得测试方法。

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM