如何在div内显示jQuery警报消息?

时间:2019-04-15 04:46:37

标签: javascript jquery html

我有以下代码计算页面内的div数量:

public class FragmentA extends Fragment {

public FragmentA() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    LinearLayout linear = new LinearLayout(getContext());
    linear.setOrientation(LinearLayout.VERTICAL);
    linear.setBackgroundColor(Color.WHITE);

    TextView tv = new TextView(getContext());
    tv.setText("Hello World1");
    linear.addView(tv);


    return inflater.inflate((XmlPullParser) linear, null);
}
}

现在,我希望将其结果显示在我制作的html div中:

jQuery(function($) {

$(document).ready(function() {
                alert( $(".contentMachine").length );
            });

});

如何将数字放在其中而不是每次页面加载时都显示警报框?

对不起!我昨天刚开始学习javascript。

3 个答案:

答案 0 :(得分:1)

赞:

$(document).ready(function() {
    $("#totalMachines").text($(".contentMachine").length);
});

答案 1 :(得分:0)

您可以使用text。在此之前,您需要使用id选择器或类选择器获取DOM元素

jQuery(function($) {
  $("#totalMachines").text(' Total ' + $(".contentMachine").length)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<span class="subtitleMain" id="totalMachines">0</span>

如果#totalMachines的初始内容为空,则也可以使用append

jQuery(function($) {
  $("#totalMachines").append(' Total ' + $(".contentMachine").length)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<div class="contentMachine">1</div>
<span class="subtitleMain" id="totalMachines"></span>

答案 2 :(得分:0)

$('#totalMachines').html('Total: '+$('.contentMachine').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="subtitleMain" id="totalMachines">0</span>
<div class="contentMachine"></div>
<div class="contentMachine"></div>
<div class="contentMachine"></div>
<div class="contentMachine"></div>