繁体   English   中英

如果选中复选框,则选择div

[英]Select div if checkbox checked

如果选中“ myCheck”中的输入复选框,如何选择“容器” div?
我正在使用jquery打印区域插件,因此,基本上,如果选中了checkbox,则需要选择容器div,因此代码应类似于$(“。myCheck input:checked> div”)。printArea();。

这是我的HTML:

<div class="content">
        <div class = "myCheck"><input type="checkbox" />
            <div class = "container"> 
                <img src="https://www.kent.ac.uk/graduateschool/images/email-thumbnail.jpg" alt="My new Image">
            </div>
            </div>
        </div>

我试过使用>选择器,但它似乎不起作用:

alert( $(".myCheck input:checked > div").printArea()

还尝试了这个:

alert( $(".myCheck input:checked").children()).printArea()

您可以使用.next()

 $('input').on('change', function(){ console.log($(".myCheck input:checked").next().html()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"> <div class = "myCheck"><input type="checkbox" /> <div class = "container"> <img src="//placehold.it/50" alt="My new Image"> </div> </div> </div> 

使用jQuery,您可以将其用作检查值:

$('.myCheck').prop('checked', true);

您可能可以使用回调函数来选择容器:

$('.myCheckbox').is(':checked', function(e){
  e.preventDefault(e);
  $('container').theMethodYouWantToUse
});

希望对你有帮助

运行以下示例,选中并取消选中该组件,希望对您有所帮助!

基本上,我对复选框的单击使用简单的回调,控制其状态,并在检查组件时选择内容。

 // Waiting for DOM load $(document).ready(function() { // Callback for checkbox's click $(".myCheck > input[type='checkbox']").on("click", function() { // Setting the container variable as null var container = null; // Checking if the checkbox is "checked" if ($(this).is(":checked")) { // Selecting the container node object, so you can use it as you want var container = $(".container"); // Console warnings console.info("Container selected, the checkbox must be checked!"); console.log("Some test information from container: " + $(container).find('span').html()); } else { // Console warnings console.info("Container not selected, the checkbox must be checked!"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"> <div class="myCheck"> <input type="checkbox" /> <div class = "container"> <span>Some example content..</span> </div> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM