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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11560028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:19:31  来源:igfitidea点击:

get the next element with a specific class after a specific element

javascriptjquerytraversal

提问by rubyprince

I have a HTML markup like this:

我有一个像这样的 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>

I want to get the next element after from dates to get the corresponding to date. (Layout is a little more complex but from date has from-date class and to date has to-date class).

我想从日期之后获取下一个元素以获取对应的日期。(布局稍微复杂一些,但从日期有从日期类,至今有至今类)。

This is I am trying to do, I want to take a from date element and find the next element in the dom with to-date class. I tried this:

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

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

but it is giving me empty jQuery element. I think this is because nextgives the next sibling matching the selector. How can I get the corresponding to-date?

但它给了我空的 jQuery 元素。我认为这是因为next给出了匹配选择器的下一个兄弟。我怎样才能得到相应的to-date

回答by techfoobar

Couldn't find a direct way of doing this, so wrote a little recursive algorithm for this.

找不到这样做的直接方法,因此为此编写了一个小递归算法。

Demo:http://jsfiddle.net/sHGDP/

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

nextInDOM()function takes 2 arguments namely the element to start looking from and the selector to match.

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

instead of

代替

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

you can use:

您可以使用:

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

Code

代码

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
}

回答by Christoph

.next('.to-date')does not return anything, because you have an additional pin between

.next('.to-date')不返回任何东西,因为你有一个额外p的中间

You need .parent().next().find('.to-date').

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

You might have to adjust this if your dom is more complicated than your example. But essentially it boils down to something like this:

如果你的 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"));
});

edit: It's much better and faster to just look for the ID. The following code searches all from-dates and gets the according to-dates:

编辑:查找 ID 更好更快。以下代码搜索所有起始日期并获取相应日期:

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));
}

Take a look at the example.

看看这个例子

回答by Tejasva Dhyani

try

尝试

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;
        }
    }
});

回答by Chung Solomon

    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;
       }
    }

Use JS. to get the key number from your id. Analysis it than output the number. Use JQ. selecter combine string with you want than + this number. Hope this can help you too.

使用JS。从您的 id 中获取密钥号码。分析它比输出数字。使用 JQ。选择器将字符串与您想要的字符串组合起来,而不是 + 这个数字。希望这也能帮到你。

回答by ariebear

I know this is an old question, but I figured I'd add a jQuery free alternate solution :)

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

I tried to keep the code simple by avoiding traversing the DOM.

我试图通过避免遍历 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'));

If you know that the to date will always be the next input element with a class of "calender", then you don't need the second loop.

如果您知道 to date 将始终是具有“calender”类的下一个输入元素,那么您不需要第二个循环。