我的函数没有产生期望的结果
my function is not producing the desired result
嗨,伙计们,我有返回锚元素的意图函数,但我有一些问题。这是我的代码:
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/开始了解可能的情况。
相关文章:
- 奇怪的Javascript结果
- Javascript(jQuery)给了我奇怪的结果
- JSONP请求返回结果,但也触发error_callback
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- Javascript,输出结果后页面不断刷新
- 这是使用html快照和谷歌获取的预期结果吗?SEO/SPA
- 将地理编码结果转换为php变量以发布到mysql数据库
- AngularJS/HTML/Bootstrap元素用于动态搜索结果
- JavaScript 变量范围不期望结果
- 茉莉花期望不匹配数组结果
- 循环访问 JSON 对象,没有得到我期望的结果
- 802.11 auth"没有得到我所期望的结果
- 我的函数没有产生期望的结果
- JavaScript表单验证代码没有给出期望的结果
- Ng-if和ng-class-even/odd不能很好地一起工作,也不能得到期望的结果
- 包含数组方法的JavaScript函数没有返回期望的结果
- Rails控制器和javascript:不要给出期望的重定向结果
- 图像旋转木马是波动的&没有给出期望的结果
- 没有得到我期望的结果
- while循环-如何将userInput转换为一个数字,并使用该数字创建一个期望的结果与javascript