Javascript条件查找/替换

Javascript条件查找/替换,javascript,Javascript,对于我的javascript项目,我有一个如下列表: <li id="1">101.33, "book name 1"</li> <li id="2">600.01, book name 2</li> <li id="3">001.11, book name 3</li> etc... // count of all LI items var elements = 0; // fetch LI item one at

对于我的javascript项目,我有一个如下列表:

<li id="1">101.33, "book name 1"</li>
<li id="2">600.01, book name 2</li>
<li id="3">001.11, book name 3</li>

etc...
// count of all LI items
var elements = 0; 
// fetch LI item one at a time
var element = document.getElementById(elements+1);
while (element != undefined) {
    // get the number
    var number = Number(getNumber(element.innerHTML));
    // do something with number and or LI element
    if (inRange(number, 100, 200)) { /* add 100 ...*/ } // and so on
    // go to next element
    elements++;
    element = document.getElementById(elements+1);
}

function getNumber(elementContent) {
    return elementContent.split(",")[0]; // TODO error handling
}

function inRange(number, min, max) {
    return (number >= min) && (number <= max);
}

尝试jQuery
。每个

$('li').each(function(index, value) {
    var val = $(this).text().split(','); //split into array
    if (index >= 100 && index < 200) {
        //do stuff
    }
    if (index >= 400 && index < 500) {
        //do stuff
    }
    //etc
});
$('li')。每个函数(索引、值){
var val=$(this.text().split(',');//拆分为数组
如果(索引>=100&&index<200){
//做事
}
如果(索引>=400&&index<500){
//做事
}
//等
});

无论您是想使用纯JavaScript还是助手库(例如jQuery)来解决这个问题,我都建议您将问题分解成更小的任务,并逐一解决。最终,他们将一个接一个地构建完整的解决方案。我将从三个简单的函数开始(阅读您的描述,它们将经常被需要):

  • 能够单独列出所有li元素
  • 从li内容中提取数字
  • 检查数字是否在给定范围内
代码可以如下所示:

<li id="1">101.33, "book name 1"</li>
<li id="2">600.01, book name 2</li>
<li id="3">001.11, book name 3</li>

etc...
// count of all LI items
var elements = 0; 
// fetch LI item one at a time
var element = document.getElementById(elements+1);
while (element != undefined) {
    // get the number
    var number = Number(getNumber(element.innerHTML));
    // do something with number and or LI element
    if (inRange(number, 100, 200)) { /* add 100 ...*/ } // and so on
    // go to next element
    elements++;
    element = document.getElementById(elements+1);
}

function getNumber(elementContent) {
    return elementContent.split(",")[0]; // TODO error handling
}

function inRange(number, min, max) {
    return (number >= min) && (number <= max);
}
//所有LI项目的计数
var元素=0;
//一次取一个项目
var element=document.getElementById(elements+1);
while(元素!=未定义){
//拿到号码了吗
var number=number(getNumber(element.innerHTML));
//用数字和/或LI元素做一些事情
if(inRange(number,100200)){/*添加100…*/}//依此类推
//转到下一个元素
元素++;
element=document.getElementById(elements+1);
}
函数getNumber(elementContent){
return elementContent.split(“,”[0];//TODO错误处理
}
范围内的函数(数字、最小值、最大值){

return(number>=min)&(number一种方法如下(使用普通JavaScript,尽管您需要使用最新的浏览器):

//首先,我们需要获取所有“li”项:
var lis=document.queryselectoral('ul>li'),
//查找此浏览器的相关文本属性:
textProp='textContent'文档中的'textContent':'innerText',
//允许评估更改的空字符串变量:
_新文本=“”;
//将项目符号列表条目重新映射到新的(一致的)标记类型(您的选择–使其看起来漂亮!)。
//你自己做这个。
//零填充数字的函数(我相信杜威十进制的要求):
函数leftPadNumber(num、numLength、padChar){
var nString=num.toString(),
major=parseInt(数值,10),
minor=parseFloat(nString.substring(nString.indexOf('.')),
diff=numLength-主要.toString()长度;
如果(差异>0){
返回新数组(diff+1).join(padChar | | 0)+(major+minor);
}否则{
返回num;
}
}
//对于100到200之间的条目,将100添加到杜威十进制数。
//对于400到500之间的条目,在杜威十进制数上加200。
//850到900之间的条目需要从杜威十进制数中删除100。
//600到650之间的条目需要在杜威十进制数中添加17
//请注意,我对“中间”作了非常字面的解释(如有必要,请修改):
函数修正deweydecimal(num){
如果(num>100&&num<200){
num+=100;
}否则如果(数值>400&&num<500){
num+=200;
}否则如果(数值>850&&num<900){
num-=100;
}否则如果(数量>600&&num<650){
num+=17;
}
//如果num不在上述约束范围内,则会发生此情况:
返回num;
}
//迭代“lis”节点列表/集合中的每个元素:
[]forEach.call(lis,函数(a){
/*使用两个
函数,并将这些函数指定给_newText变量:
_newText=a[textProp].replace(/(\d{3}\.\d{2})/,函数(m){
返回leftPadNumber(修正的deWeydecimal(parseFloat(m)).toFixed(2),3);
});
//对于更改的项目,将“更改”附加到记录中。
//对于未更改的项目,请在记录中附加“未更改”。
//将原始文本与“(无更改)”一起返回到元素
//(如果“a[textProp]”正好等于“_newText”)或带有“(changed)”
//(如果两个变量不相同):
[textProp]=“newText+”(“+”([textProp]=“a[textProp]?“无更改”:“已更改”)+”);
});
//对于不正确的记录,请在记录后附加“无效记录”
//我完全不知道如何评估“不正确”的记录。

参考资料:


对于初学者,请查看,不要使用查找/替换-否则在本例中就不需要javascript。谢谢。有些记录没有数字,因此我假设这些记录无效。我还忘了提到我应该在页面上添加一个按钮来执行更正。这样做的问题是….?你在哪里你卡住了,你试过什么?上面我做的,或多或少是为了好玩,因为它看起来很有趣。剩下的看起来很简单,所以我不确定你为什么会有问题。我唯一被你发送的东西卡住了,就是让号码改变。“改变”的文字起作用,但记录的号码保持不变,是的:那是b因为我将原始文本(
a[textProp]
)放回元素中,而不是
\u newText
(保存更改的数字)。抱歉,我写出来的时候显然太困了。我刚才所做的编辑和更新现在应该可以工作了;当然,我已经更正了答案中代码中的错误。对于我的困惑和愚蠢,我感到抱歉……”无需道歉,您提供了很好的洞察力。问题是-我一直在尝试在amendedDeweyDecimal函数中包含一个条件,用于没有记录编号的实例。我得到了以下信息:
else if(typeof num!=='undefined'){num=='Invalid record';}
但还没有让它起作用。有什么提示吗?
// first, we need to get all the 'li' items:

var lis = document.querySelectorAll('ul > li'),
    // find the relevant text-property for this browser:
    textProp = 'textContent' in document ? 'textContent' : 'innerText',
    // empty string variable to allow assessment of changes:
    _newText = '';

// Remap the bullet list entries to a new (consistent) tag type (your choice – make it look pretty!).
// do this one yourself.

// a function to zero-pad the numbers (I believe a requirement of Dewey Decimal):
function leftPadNumber(num, numLength, padChar) {
    var nString = num.toString(),
        major = parseInt(num, 10),
        minor = parseFloat(nString.substring(nString.indexOf('.'))),
        diff = numLength - major.toString().length;
    if (diff > 0) {
        return new Array(diff + 1).join(padChar || 0) + (major + minor);
    } else {
        return num;
    }

}

// For entries between 100 and 200, add 100 to the Dewey decimal number.
// For entries between 400 and 500, add 200 to the Dewey decimal number.
// Entries between 850 and 900 need to have 100 removed from the Dewey decimal number.
// Entries between 600 and 650 need to have 17 added to the Dewey decimal number

// note that I've taken a very literal interpretation of 'between' (amend if necessary):
function amendedDeweyDecimal(num) {
    if (num > 100 && num < 200) {
        num += 100;
    } else if (num > 400 && num < 500) {
        num += 200;
    } else if (num > 850 && num < 900) {
        num -= 100;
    } else if (num > 600 && num < 650) {
        num += 17;
    }
    // happens if num falls somewhere outside of the above constraints:
    return num;
}

// iterates over each element in the 'lis' nodeList/collection:
[].forEach.call(lis, function (a) {
    /* replaces the found numbers ('m') in the string, using the two
       functions, above, and assigns those to the _newText variable:
    _newText = a[textProp].replace(/(\d{3}\.\d{2})/, function (m) {
        return leftPadNumber(amendedDeweyDecimal(parseFloat(m)).toFixed(2), 3);
    });

    // For items that get changed, append “changed” to the record.
    // For items that do not get changed, append “no change” to the record.

    // returns the original text to the element, along with '(no change)'
    // (if 'a[textProp]' is exactly equal to '_newText') or with '(changed)'
    // (if the two variables are not identical):
    a[textProp] = _newText + ' (' + (_newText === a[textProp] ? 'no change' : 'changed') + ')';
});

// For records that are incorrect, append “invalid record” to the record
// I have absolutely no idea how to assess an 'incorrect' record.