0

我有这个 switch 语句:

var currency = "";

switch (row.currency) {
case 1 :
    currency = "£";
    break;
case 2 :
    currency = " $";
    break;
case 3 :
    currency = "€";
    break;

default:
    currency = "£";
    break;
}

然后我尝试在currency这里参考:

<td>' + currency + '<input class="editinput number" type="text" value="' + row.adhoc_setup_rem_cost + '" name="changes[' + row.id + '][adhoc_setup_rem_cost]" /></td>

但是当我查看它时,我只会在输入框之前看到“未定义”这个词,而不是货币符号......

4

3 回答 3

0

作为对 rps 的回应,也是对 OP 问题的回答。我会避免使用 a switch,而只是使用数组。由于row.currency将始终为 1、2 或 3,因此您可以轻松地将包含相应值的数组分配给currency

var currency = ['&pound;','&pound;','&#36;','&euro;'];//default value is 0
//concat into string like so:
'<td>' + currency[+(row.currency) || 0] + '<inp...';

我在这里所做的确实假设row.currency强制转换为数字时,将永远不会产生高于 3 的值,因为如果确实如此,您将连接undefined到字符串中。为避免这种情况,只需执行以下操作:

'<td>' + currency[+(row.currency)] || currency[0] + '<inp...';

这样,上面的表达式将始终默认为'&pound;'. 不过,总的来说,我必须说您的代码对我来说看起来很奇怪。说得客气一点。您似乎正在用 JavaScript 生成 HTML,这很可能会在客户端运行。在使用 PHP 时生成 HTML(正如您的标题暗示您正在使用 PHP)比您目前正在做/尝试做的任何事情都要好得多。

假设您使用查询数据库PDO

$currency = array(1 => '&pound;', 2 => '&#36;', 3 => '&euro;');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
    $row->currency = isset($currency[$row->currency]) ? $row->currency : 1;//default 1
    echo '<tr><td>'. $currency[$row->currency].'</td>';
}

也就是说,我真的无法确定在您的情况下最好的方法是什么,因为您确实需要提供更多详细信息:您发布的代码应该在哪里运行,它应该做什么......?

于 2013-07-26T11:19:46.240 回答
0

我不知道这里的 row.currency 是什么。但我试过这个,它对我来说很好。

$(document).ready(function() {
 var currency = "";
 var row={currency:1};
 switch (row.currency) {
 case 1 :
         currency = "&pound;";
         break;
 case 2 :
         currency = " &#36;";
         break;
 case 3 :
         currency = "&euro;";
         break;

 default:
         currency = "&pound;";
          break;
 }

 $('<td>'+currency+'<input type="text"> </td>').insertAfter("p");
});

所以可能是你的问题row.currency。所以再次检查或分享您的代码。

于 2013-07-26T09:35:19.963 回答
0

从您的 html 代码中删除货币并在将 id 添加到 td 后将其添加到您的脚本代码中

var txt = document.createTextNode(currency);  
document.getElementById('tdID').appendChild(txt);
于 2013-07-26T10:03:41.080 回答