在特定元素之后获取具有特定类的下一个元素

时间:2012-07-19 11:37:03

标签: javascript jquery traversal

我有这样的HTML标记:

<p>
  <label>Arrive</label>
  <input id="from-date1" class="from-date calender" type="text" />
</p>

<p>
  <label>Depart</label>
  <input id="to-date1" class="to-date calender" type="text" />
</p>

<p>
  <label>Arrive</label>
  <input id="from-date2" class="from-date calender" type="text" />
</p>

<p>
  <label>Depart</label>
  <input id="to-date2" class="to-date calender" type="text" />
</p>

我希望从日期之后获取下一个元素以获得相应的日期。 (布局稍微复杂一些,但是从日期开始,从日期开始,到日期已经到了日期类)。

这是我想要做的,我想从日期元素中获取并使用to-date类查找dom中的下一个元素。我试过这个:

$('#from-date1').next('.to-date')

但它给了我空的jQuery元素。我认为这是因为next给出了与选择器匹配的下一个兄弟。如何获得相应的to-date

5 个答案:

答案 0 :(得分:8)

无法找到直接的方法,所以为此写了一个小的递归算法。

演示: http://jsfiddle.net/sHGDP/

nextInDOM()函数有2个参数,即要开始查找的元素和要匹配的选择器。

而不是

$('#from-date1').next('.to-date')

你可以使用:

nextInDOM('.to-date', $('#from-date1'))

<强>代码

function nextInDOM(_selector, _subject) {
    var next = getNext(_subject);
    while(next.length != 0) {
        var found = searchFor(_selector, next);
        if(found != null) return found;
        next = getNext(next);
    }
    return null;
}
function getNext(_subject) {
    if(_subject.next().length > 0) return _subject.next();
    return getNext(_subject.parent());
}
function searchFor(_selector, _subject) {
    if(_subject.is(_selector)) return _subject;
    else {
        var found = null;
        _subject.children().each(function() {
            found = searchFor(_selector, $(this));
            if(found != null) return false;
        });
        return found;
    }
    return null; // will/should never get here
}

答案 1 :(得分:4)

.next('.to-date')不会返回任何内容,因为您之间还有一个p

您需要.parent().next().find('.to-date')

如果你的dom比你的例子更复杂,你可能需要调整它。但基本上归结为这样的事情:

$(".from-date").each(function(){
    // for each "from-date" input
    console.log($(this));
    // find the according "to-date" input
    console.log($(this).parent().next().find(".to-date"));
});

编辑:只需查找ID就好多了。以下代码搜索所有from-dates并获取相应的日期:

function getDeparture(el){
    var toId = "#to-date"+el.attr("id").replace("from-date","");
    //do something with the value here
    console.log($(toId).val());
}

var id = "#from-date",
    i = 0;

while($(id+(++i)).length){
    getDeparture($(id+i));
}

查看example

答案 2 :(得分:0)

var flag = false;
var requiredElement = null;
$.each($("*"),function(i,obj){
    if(!flag){
        if($(obj).attr("id")=="from-date1"){
            flag = true;
        }
    }
    else{
        if($(obj).hasClass("to-date")){
            requiredElement = obj;
            return false;
        }
    }
});

答案 3 :(得分:0)

    var item_html = document.getElementById('from-date1');
    var str_number = item_html.attributes.getNamedItem("id").value;
    // Get id's value.
    var data_number = showIntFromString(str_number);


    // Get to-date this class
    // Select by JQ. $('.to-date'+data_number)
    console.log('to-date'+data_number);

    function showIntFromString(text){
       var num_g = text.match(/\d+/);
       if(num_g != null){
          console.log("Your number:"+num_g[0]);
          var num = num_g[0];
          return num;
       }else{
          return;
       }
    }

使用JS。从你的身份证中获取密钥号码。分析它比输出数字。使用JQ。选择组合字符串与你想要的比+这个数字。希望这也可以帮到你。

答案 4 :(得分:0)

我知道这是一个老问题,但是我想我会添加一个jQuery免费替代解决方案:)

我试图通过避免遍历DOM来简化代码。

let inputArray = document.querySelectorAll(".calender");

function nextInput(currentInput, inputClass) {
    for (i = 0; i < inputArray.length - 1; i++) {
        if(currentInput == inputArray[i]) {
            for (j = 1; j < inputArray.length - i; j++) {
                //Check if the next element exists and if it has the desired class
                if(inputArray[i + j] && (inputArray[i + j].className == inputClass)) {
                    return inputArray[i + j];
                    break;
                }
            }
        }
    }   
}

let currentInput = document.getElementById('from-date1');

console.log(nextInput(currentInput, 'to-date calender'));

如果您知道“迄今为止”将始终是具有“日历”类的下一个输入元素,那么您就不需要第二个循环。

相关问题