javascript 在javascript中获取附近的兄弟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14477791/
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-10-26 21:44:05  来源:igfitidea点击:

get nearby sibling in javascript

javascriptdomsiblings

提问by

I have a certain DIV structure with an anchor tag in between somewhere. On click of the link, I need to fetch the value of another spanelement within the parent divand do something, (say, alert it).

我有一个特定的 DIV 结构,中间有一个锚标记。单击链接时,我需要获取span父元素中另一个元素的值div并执行某些操作(例如,提醒它)。

The html is like this :

html是这样的:

...
<div id="div1">
  ...
  <span>This is reqd</span>
  ...
  <a href="#">Click Me </a>
  ...
</div>
...

The entire divis repeated many times in the page. When I click on the aI want to alert "This is reqd".

整个div页面在页面中重复多次。当我点击a我想提醒“这是需要的”时。

Can the HTML be searched like this?

可以这样搜索 HTML 吗?

采纳答案by Riju Mahna

For a single span element, it should be pretty easy,. Just call a myFunction(this) on click of the link and manipulate the DOM like this :

对于单个跨度元素,它应该很容易。只需在单击链接时调用 myFunction(this) 并像这样操作 DOM:

function myFunction(currObj){
var parentofSelected = currObj.parentNode; // gives the parent DIV

var children = parentofSelected.childNodes;
for (var i=0; i < children.length; i++) {
    if (children[i].tagName = "span") {
        myValue= children[i].value;
        break;
    }
}
alert(myValue); // just to test

 } // end function

Hope this works. It did for me !!

希望这有效。它对我有用!!

回答by jAndy

Since the <span>is not the immediate siblingof that <a>, we can't invoke .previousSiblingor .previousElementSibling. Best solution might be to get the parent and query for the <span>

由于<span>不是that的直接兄弟,所以<a>我们不能调用.previousSiblingor .previousElementSibling。最好的解决方案可能是获取父项并查询<span>

document.getElementById( 'div1' ).getElementsByTagName( 'a' )[ 0 ].addEventListener('click', function() {
    alert( this.parentNode.getElementsByTagName( 'span' )[ 0 ].textContent );
}, false);

Demo: http://jsfiddle.net/cEBnD/

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

回答by rsp

Update: Solutions with and without jQuery

更新:使用和不使用 jQuery 的解决方案

This answer got so many downvotes for showing an example with jQuery that I decided to add more examples with vanilla JavaScript so that anyone could choose whether to use jQuery or not.

这个答案因为用 jQuery 展示了一个例子而得到了很多反对,我决定添加更多带有 vanilla JavaScript 的例子,这样任何人都可以选择是否使用 jQuery。

Generally, you can use .previousSiblingin vanilla JavaScript, see:

通常,您可以.previousSibling在 vanilla JavaScript 中使用,请参阅:

and you can use .prev()in jQuery, see:

您可以.prev()在 jQuery 中使用,请参阅:

But keep in mind that those may not work in more complicated cases when you don't know the exact structure of your entire DOM.

但是请记住,当您不知道整个 DOM 的确切结构时,这些在更复杂的情况下可能不起作用。

Here are few examples of achieving that goal both using jQuery and with vanilla JavaScript, for simple cases with fixed DOM structure and for more complicated cases using classes.

以下是使用 jQuery 和 vanilla JavaScript 实现该目标的几个示例,适用于具有固定 DOM 结构的简单情况以及使用类的更复杂情况。

Without classes

不上课

For the most simple DOM structures you might get away with putting event listeners on all links and relying on the implicit knowledge of the DOM, but this may not work for more complex situations - for those see the examples with classes below.

对于最简单的 DOM 结构,您可能会在所有链接上放置事件侦听器并依赖于 DOM 的隐式知识,但这可能不适用于更复杂的情况 - 对于那些请参见下面的类示例。

With jQuery:

使用 jQuery:

$('a').click(function () {
  alert( $(this).prev().text() );
  return false;
});

See DEMO.

演示

Without jQuery:

没有 jQuery:

document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', () => {
    alert(link.previousSibling.previousSibling.innerText);
  });
});

Note that the previousSiblinghas to be used twice, because the empty text node that is between tha span and link would be used otherwise.

请注意,previousSibling必须使用两次,因为否则将使用跨度和链接之间的空文本节点。

See DEMO.

演示

Using classes

使用类

If the spanis not immediately preceding your aelement then you may also want to do it a little bit differently, also adding some classes to make sure that your code doesn't break any other links on the page:

如果span不是紧接在您的a元素之前,那么您可能还想以不同的方式进行操作,同时添加一些类以确保您的代码不会破坏页面上的任何其他链接:

With jQuery:

使用 jQuery:

$('a.link').click(function () {
  alert( $(this).parent().find('span.text').text() );
  return false;
});

See DEMO.

演示

Without jQuery:

没有 jQuery:

document.querySelectorAll('a.link').forEach(link => {
  link.addEventListener('click', () => {
    alert(link.parentNode.querySelector('span.text').innerText);
  });
});

See DEMO.

演示

The above code will bind click handlers to every aelement with class "link" which will alert a text contained by its sibling spanelement with a class "text". (Of course the class names should be more descriptive than that.)

上面的代码将点击处理程序绑定到每个a具有“link”类的元素,这将span用“text”类警告由其同级元素包含的文本。(当然,类名应该比这更具描述性。)

回答by George Livingston

<html>
<body>
    <div id="div1">
        <span>This is required</span>
        <a href="#" onclick="myclick(this.parentNode)">Click Me</a>
    </div>
</body>
<script>
    function myclick(x){
        var y = x.querySelector("span").innerHTML;
        alert(y)
    }
</script>
</html>

insted of spanyou can also give class nameeg.,

insted的的跨度,你也可以给类名例如,

<span class="classname">This is required</span>
x.querySelector(".classname").innerHTML

回答by Itisha-systematix

Using jQuery:

使用jQuery:

$('#innerId').siblings()