我有以下代码,它将字符串添加到数组中:
sql = new Array();
query = "SELECT * FROM specimen";
$('#keyword').change(function(){
filter = " MATCH(clinical_history) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(specimen) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(macroscopic) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(microscopic) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(conclusion) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(comment) AGAINST ('_KEYWORD_' IN BOOLEAN MODE)";
sql.push(filter);
});
然后我用输入字段的值替换上面字符串中的_KEYWORD_
占位符:
$('#search_container').on('click', '#search_btn', function(){
keyword = $('#keyword_field').val();
var regExp = new RegExp('_KEYWORD_', 'g');
$.each(sql, function(index, value) {
sql[index] = value.replace(regExp, keyword);
if(sql != ''){
query += " WHERE " + sql.join(' AND ');
}
});
现在一次工作正常,但是当_KEYWORD_
占位符被输入值替换时却没有。我需要做的是确定最后一个输入值并在替换代码中使用它。
我有什么想法可以做到这一点吗?
答案 0 :(得分:1)
最后一个输入值在字符串中可能不唯一。它可能与作为sql查询一部分的其他单词相同。试图这样做既困难又不保证100%可靠。
我建议您在进行任何替换之前单独保存原始模板字符串,以便始终拥有该原始模板。然后,您可以每次都以相同的方式进行更换。简单且100%可靠。
构造它的一种方法是使sql Array的每个元素成为一个具有两个属性的对象,即模板字符串和转换/替换字符串。然后,你将永远都有。
var sql = [];
$('#keyword').change(function(){
var obj = {};
obj.filter = " MATCH(clinical_history) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(specimen) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(macroscopic) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(microscopic) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(conclusion) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(comment) AGAINST ('_KEYWORD_' IN BOOLEAN MODE)";
sql.push(obj);
});
$('#search_container').on('click', '#search_btn', function(){
var keyword = $('#keyword_field').val();
var regExp = new RegExp('_KEYWORD_', 'g');
$.each(sql, function(index, value) {
// store the replacement string as the .replaced property
// so the .filter property remains unchanged and can be used
// again in the future
sql[index].replaced = sql[index].filter.replace(regExp, keyword);
});
if (sql.length) {
var q = $.map(sql, function(elem) {
return elem.replaced;
});
query += " WHERE " + q.join(' AND ');
}
});