上下文:
我需要获取TD元素中的一些动态ID,将其作为参数传递并调用特定函数。
我在TD中添加了一个类( .calcStartPrice ),这样可以帮助我在元素内部进行迭代:
var inputEl, eventStartPrice, exchangeRate, convertedStartPriceEl, currSymbol, decimalPlaces;
jQuery(".calcStartPrice").each(function (i,e) {
jQuery(e).find('span, input').each(function (a,b) {
console.info(b.id);
});
});
当我运行此代码时,我有以下ID:
eventStartPrice_S20_L10140
S20_L10140_startPrice
exchangeRate_S20_L10140
curSymbol_S20_L10140
decPlaces_S20_L10140
converted_StartPrice_S20_L10140
现在,我想做的是检查id是否以eventStartPrice开头,以便我将id归因于变量。
我尝试了什么:
var eventStartPrice;
jQuery(".calcStartPrice").each(function (i,e) {
jQuery(e).find('span, input').each(function (a,b) {
//console.info(b.id);
if (jQuery(b[id^="eventStartPrice"])) { //this is wrong!!!
eventStartPrice = b.id;
console.info(eventStartPrice);
}
});
});
但它不起作用...... 如果id以某个字符串开头,我怎样才能检查第二次迭代?
答案 0 :(得分:2)
替换:
if (jQuery(b[id^="eventStartPrice"])) { //this is wrong!!!
使用:
if (/^eventStartPrice/.test(b.id)) {
答案 1 :(得分:1)
试试这个:
$(b).is("[id^='eventStartPrice']")
基本上,b不是普通对象,需要将其包装到jQuery对象中,以便可以对其执行操作。或者,更确切地说,当你没有将b作为jQuery对象时,你会尝试访问它。
答案 2 :(得分:1)
您可以使用regexp:
if (b.id.match(/^eventStartPrice/)))
答案 3 :(得分:0)
使用jquery split方法
id_val = b.id
name = id_val.split('_');
现在name[0]
将包含'_'之前的字符。
您可以使用if语句
if(name[0] == "eventStartPrice")
{
......
}
答案 4 :(得分:0)
当你使用jQuery时,你会得到dom元素。如果你然后创建一个jQuery对象,你可以应用所有的魔法。这就是你的代码中缺少的东西。所以这是我的sugestion如何重写你的功能。
var eventStartPrice;
jQuery(".calcStartPrice").each(function (i,e) {
jQuery(e).find('span, input').each(function (a,b) {
var $this = jQuery(this);
if ($this.is("[id^=eventStartPrice]")) {
eventStartPrice = $this.attr("id");
console.info(eventStartPrice);
}
});
});
你可以在fiddle
中测试一下