【问题标题】:How to loop through all elements jQuery如何循环遍历所有元素jQuery
【发布时间】:2015-09-30 12:24:14
【问题描述】:

我有图片,必须计算每张图片的 Facebook 份额。我不能为此做循环。现在只针对一个元素。怎么做? 我的代码是:

        <script>
        $(document).ready(function(){
        	var current = 0;
        	$count = $('#count_bombs').val();
        	$('#' + current).each(function() {
        		var id = $('#' + current).val(); console.log(id);
        		$.getJSON('https://graph.facebook.com/http://example.com/images/view/' + id, function(data) { 
        		   document.getElementById("shares_count_" +current).innerHTML = data.shares;
        		  console.log(data.shares);  console.log("#shares_count_" +current);
        		});
        		current++;
        	});

        });
        </script>
        <?php $num=0;  $id = 0; ?> 
        		<?php foreach($images as $key=>$val){  ?>
        <div>
        <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo URL::base();?>images/view/<?php echo $val['image_name'];?>">
        <span aria-hidden="true"  class="glyphicon glyphicon-link"></span>
        	<input type="hidden" id="<?php echo $id; ?>" class="count" value="<?php echo $val['image_name'];?>">
        	SHARE	
        </a>
         </div>

        <div>
       <span class="glyphicon glyphicon-comment" aria-hidden="true" ></span> 
        	<span id="shares_count_<?php echo $id; ?>"></span>
        	<input type="hidden" value="<?php echo count($bombs);?>" id="count_bombs" name="count_bombs">
       </div>

已编辑:我做到了。我使用了每个方法的index 参数。这是我的代码:

<script>
$(document).ready(function(){
	var current = 0;
	$("input[type=hidden]").each(function(index, element){
		var id = $('#' + current).val();
		$.getJSON('https://graph.facebook.com/http://pbombd.dev/bombs/view/' + id, function(data) { 
		   $('#shares_count_' + index).html(data.shares);
		});
		current++;
	});

});
</script>

【问题讨论】:

  • 提示:不要在每个中使用 id 选择器,而是尝试使用类选择器..

标签: javascript jquery loops each


【解决方案1】:

$('#' + count) 将只返回一个元素,因此无法循环。似乎您想在页面中使用 css 类 count 找到每个隐藏的输入。你可以这样做:

$('input.count').each(function() {
    $input = $(this);

    // $input contains the hidden input
    console.log($input.attr('id));
});

【讨论】:

  • 我认为 jQuery 有一个 find 方法,它返回与选择器匹配的元素数组。那么也许只是在做 $(rootEl).find(selector).length ?
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 2010-10-28
  • 2018-04-13
  • 2018-06-05
  • 2013-07-22
  • 1970-01-01
相关资源
最近更新 更多