如何编写if语句来检查jquery中的多个text()值

时间:2014-09-27 20:03:45

标签: jquery

我有一个表列,根据文本值执行特定操作。以下是html:

<td class="product"><span class="product">customer</span></td>
<td class="product"><span class="product">customer</span>, <span class="product">specifics</span></td>

<td class="product"><span class="product">admin</span>, <span class="product">specifics</span></td>

现在,我试图为某些文本值写一个条件。如果值为"customer and/or specifics",我想创建一个对话框,否则如果值为"admin",我想导航到主页面。这是js:

var rows = $(this).parents('tr');
if (rows.find('td.product').has('span.product').text() === 'customer') {

    alert('show dialog message');

} else {
    alert('navigate back to main page');
}

但是,此代码仅检查"customer"的值(但显而易见),而不检查其余值。如何检查所有文本值并相应地执行操作?有任何想法吗?? 感谢

修改

我只是想澄清一些事情: 文本val可以包含多个值,例如:"customer, specifics,admin"一行,它也可以仅包含"customer""specifics"。因此,如果任何文本值包含admin作为值,我会将其重定向到主页面。(在我的情况下是第二个条件)。仅当行包含admin以外的值时,才应显示对话框消息(在这种情况下为第一个条件)。很抱歉一开始不清楚。

2 个答案:

答案 0 :(得分:1)

试试:http://jsfiddle.net/csdtesting/ocju73ox/4/

var toredirect = false;
var showdialog = false;
//test scenarios
//var val = "admin";//works perfect
//var val = "customer, specifics"; //works perfect
//var val = "admin, specifics"; // shouuld redirect to main page, but calls dialog
var val = "admin, customer";// shouuld redirect to main page, but calls dialog

//var val = "customer, specifics";//works perfect
//var val = "customer";//works perfect

//rows.find('td.product').has('span.product').text();
// considering the text value is "admin, specifics" , 3rd <td>
alert(val);
if (checkif(val, "customer") || checkif(val, "specifics")) {
    showdialog = true;
}
if (checkif(val, "admin"))  {
   toredirect = true;
}

/*alert(toredirect);
alert(showdialog);*/

if (toredirect) {
    //redirect
    alert("will redirect");
    return false;
} else if (showdialog) {
    alert("will show dialog");
    //showdialog
}

function checkif(input, word) {
    if (input.indexOf(word) > -1) {       
        return true;     
    } else {
        return false;
    }

修订版问1:http://jsfiddle.net/csdtesting/th3Lazfj/2/

修订版问2:http://jsfiddle.net/csdtesting/th3Lazfj/4/

答案 1 :(得分:0)

试试这个:http://jsfiddle.net/hiteshbhilai2010/2nd215c3/6/

var rows = $(this).parents('tr');
var arrClass = ["product","product","product","product"];
if (rows.find('td.product').has('span.product').text() === 'customer')
               {

               alert('show dialog message');

               }else{
               alert('navigate back to main page');}
//try this 
jQuery("span.product").each(function(){
$(this).text();

    if ($(this).text() === 'customer')
               {

               alert('show dialog message');

               }else{
               alert('navigate back to main page');}

})