Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何组合使用or运算符的两个if语句_Javascript_Jquery_Logic - Fatal编程技术网

Javascript 如何组合使用or运算符的两个if语句

Javascript 如何组合使用or运算符的两个if语句,javascript,jquery,logic,Javascript,Jquery,Logic,下面的代码试图确定子H1或H2元素是否包含可分配给变量的文本,如果不包含,则默认为父元素文本: if($(this).children('h1').length){ markerCon[markerNum] = $(this).children('h1').text(); } else if($(this).children('h2').length){ markerCon[markerNum] = $(this).children('h2').text(); } else {

下面的代码试图确定子
H1
H2
元素是否包含可分配给变量的文本,如果不包含,则默认为父元素文本:

if($(this).children('h1').length){
    markerCon[markerNum] = $(this).children('h1').text();
} else if($(this).children('h2').length){
    markerCon[markerNum] = $(this).children('h2').text();
} else {
    markerCon[markerNum] = $(this).text();
}
这是可行的,但我正在努力改进我的代码,据我所知,我可以使用运算符来确定相同的内容,如下所示:

if($(this).children('h1').length || $(this).children('h2').length){
    // how do I write this part?
} else {
    markerCon[markerNum] = $(this).text();
}

我不理解的部分是如何编写语句的then部分,告诉变量从哪个H元素抓取文本。有人能帮忙吗?

我没有测试这个,但我相信它会对更短的代码做同样的测试

markerCon[markerNum] = $(this).children('h1').text() || $(this).children('h2').text();
markerCon[markerNum] = markerCon[markerNum] || $(this).text();

这确实假设如果
h1
h2
存在,则其中的文本不是空字符串。

我认为您只是在使代码复杂化。是吗?我原以为使用OR运算符可以改进我的代码,但如果大家一致同意不使用它,那么我会的!(仍在学习)您的代码仍然很好,由于您仅根据一个条件将某些内容分配给markerCon,因此无法使用或//如何编写此部分?:编写第一个示例中的代码:-)如果您有多个“If-else”,则可以使用“switch”。尝试运行缩小器并查看其输出:可以只执行
markerCon[markerNum]=$(this)。子级('h1,h2').text()| |$(this).text();
与这些conditions@megawac我在问题中遵循了
if
的逻辑。如果存在
h1
则不使用
h2
,但在您的示例中
markerCon[markerNum]
将同时使用这两个字符串。