我的函数没有产生期望的结果

my function is not producing the desired result

本文关键字:期望 结果 函数 我的      更新时间:2023-09-26

嗨,伙计们,我有返回锚元素的意图函数,但我有一些问题。这是我的代码:

 jQuery(document).ready(function ()  {
                    var myDiv = document.querySelector('.div1').childNodes;
                 	var anchor;
	               myAnchor = (function ()  {
	                              var i = 0;
		                          for (i = 0; i < myDiv.length; i++)  {
		                          anchor = myDiv[i];
			
			                      if (anchor.nodeName == 'a')  {
			                     return anchor;
			                      }else{
			                      return myDiv[i];
			                       }
		                             }   
	
	                     })();
                       console.log(myAnchor);
                        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
		   <div class="div1">
		        <p>This is the first paragraph inside the division</p>
			   <p>This is the second paragragh inside the division</p>
			   <h5>This is a h5 header</h5>
		       <p>This is a paragraph next to he h5 header</p>
		       <a href="#">justklick</a>
		   </div>		   
		</nav>

有人应该告诉我怎样才能达到我的目标。我实际上想把锚作为div的祖先来访问。

使我的问题更清楚。我知道jQuery使事情变得简单。但我的意图是迭代父元素,这是div与class=div1。并将结果设置为锚。为了确保函数返回锚标记,我使用了if语句来检查锚标记现在是否等于a标记,函数应该返回。我打算使用javascript, jQuery准备函数纯粹是为了让dom准备好。朋友们,我做的对吗?

既然你已经在使用jQuery,为什么不使用它来选择锚呢?

jQuery(document).ready(function () {
  var myAnchor = jQuery('.div1 a');
}

myAnchor[0]将给你dom元素(而不是jQuery对象)。

jQuery(document).ready(function() {
  //Thhis function returns a list of A tags in the div
  function myAnchor() {
    return jQuery('.div1 a').toArray()
  }
  console.log(
    //Get list
    myAnchor()
  );
  console.log(
    //Get first A element
    myAnchor()[0]
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <div class="div1">
    <p>This is the first paragraph inside the division</p>
    <p>This is the second paragragh inside the division</p>
    <h5>This is a h5 header</h5>
    <p>This is a paragraph next to he h5 header</p>
    <a href="#">justklick</a>
  </div>
</nav>

使用jquery非常简单:

 <div id="firstDiv">
    <a href="someurl.htm" class="foundItem">test</a>
</div>
<div id="secondDiv">
    <a href="someOtherUrl.htm" class="foundItem">test another one</a>
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){    
    var item = $("#firstDiv a.foundItem");
    alert(item.html()); // Will result in "test"
    var item2 = $("#secondDiv a.foundItem");
    alert(item2.html()); // Will show "test another one"
)};
</script>

如果你用javascript做任何事情,jQuery为你节省了大量的时间,值得投入精力好好学习。从http://api.jquery.com/browser/开始了解可能的情况。