简体   繁体   English

显示div何时获得选择或选项

[英]Show when div got select or option

I have an application with info page and edit page the info page shows the info. 我有一个带有信息页面和编辑页面的应用程序,信息页面显示信息。 in the edit page i have fields with selectbox etc etc 在编辑页面中,我有带有选择框等的字段

I want to use same code for both. 我想为两者使用相同的代码。 So I tried 所以我尝试了

if($('#product').has('option'))
{
    console.log('hasSelect')
}
else{
    console.log('NOSELECTNO')
    }

in single page there is no option or select avaible but in the edit it is. 在单个页面中没有选项或选择可用,但在编辑中是可用的。

How can I make sure it will work (and why is this not working) 我如何确保它会起作用(为什么不起作用)

edit tried this 2: 编辑尝试了这个2:

var attr = $('#product div').attr('select');

if (typeof attr !== typeof undefined && attr !== false) {
    console.log("welmetselect")
}
else
{
    console.log("zonderselect")
}

EDIT: HTML 编辑:HTML

<div id= product>
    <div>some more divs</div>
    <div> in 1 of the div we have <select><option></option></select></div>
</div>

And html infopage 和html信息页

<div id= product>
    <div>only information</div>
    <div>only text </div>
</div>

I think you need something like this: 我认为您需要这样的东西:

if ($("#product option").length )

If you don't have an option, the length will be 0 (and therefore false) 如果没有选项,则长度为0(因此为false)

First of all, you could just give them different IDs, or a class like .info and .edit , and simply check $('#product').hasClass('info') . 首先,您可以给它们提供不同的ID,或提供类似.info.edit的类,然后只需检查$('#product').hasClass('info') I do not recommend checking for a specific descendant to identify an element anyway, because you want your code to be as flexible as it can be, and if you decide to add a select element to your info page in the future, for example, to filter out specific items to get info on, your code totally breaks. 我不建议仍然检查特定的后代以标识元素,因为您希望代码尽可能地灵活,并且如果您决定将来在信息页面中添加选择元素,例如过滤掉特定项目以获取信息,您的代码将完全中断。

Second, why your code is not working, is this. 其次,这是为什么您的代码无法正常工作的原因。

var attr = $('#product div').attr('select');

select is not an attribute, it's a child. select不是属性,而是一个孩子。 Use children('select') (if it's a direct child) or find('select') (if it's not a direct child). 使用children('select') (如果它是直子)或find('select') (如果它不是直子)。

As a sidenote, you can simplify typeof attr !== typeof undefined to typeof attr !== 'undefined' because we already know typeof undefined is returning 'undefined' . 作为附带说明,您可以将typeof attr !== typeof undefined简化为typeof attr !== 'undefined'因为我们已经知道typeof undefined返回'undefined'

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

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