如何根据显示的用户文本禁用输入字段?

时间:2012-09-01 20:33:30

标签: javascript greasemonkey firefox2

我有以下代码片段:

var oldInput = document.getElementsByName ("prio");
oldInput[0].setAttribute ("disabled", "disabled");

这是相关的目标网页HTML(更正):

<div id="content">
    <p>(CONTENT)</p>
    <form>
      <p>Priority: <input name="prio" type="text" value="285"></p>
      <p>Success: <input name="succ" type="text" value="6"></p>
    </form>
</div>
<table border="0" cellspacing="0" width="100%">
    <tbody>
        <tr>
            <td class="user">
            &nbsp;
            <a href="#" class="nav" title="Logout John">Logout</a>

            &nbsp;(User: John)
            </td>
        </tr>
    </tbody>
</table>

请见jsfiddle.net/Kc3BB/3

我有很多用户的1个接入点。但我希望5个用户能够更改prio值。您可以看到用户名在页脚中。

是否有可能在javascript中使用上面的代码为Firefox 2.x并且没有jQuery?

示例:

if USER (from footer) == JOHN || LUKE || JEFF || MAX || ANDY
do nothing

else
disable PRIO BOX (from content)

3 个答案:

答案 0 :(得分:1)

试试这个:

var tds = document.getElementsByTagName("TD",
    footerText = tds[tds - 1].textContent,
    user = footerText.match(/\(User: ([^\)]*\))/)[1].toUpperCase();

if (" JOHN LUKE JEFF MAX ANDY ".indexOf(" " + user + " ") !== -1) {
    // Do stuff
} else {
    // Do else stuff
    var oldInput = document.getElementsByName("prio");
    oldInput[0].setAttribute("disabled", "disabled");
}

注意:您的伪代码与您在单词中所说的完全相反。将上述代码修复为您的实际需求。

编辑:我不记得Firefox 2是否支持数组indexOf。确实如此。所以你可以改用这一行:

if (["JOHN", "LUKE", "JEFF", "MAX", "ANDY"].indexOf(user) !== -1) {

编辑2 :我刚刚看到您的编辑并相应地更改了答案。我希望您的HTML代码段实际上反映了网页的来源,或者发现页脚元素需要其他方法。

答案 1 :(得分:1)

var allowed_users = ['John', 'Luke', 'Jeff', 'Max', 'Andy'];
var user = /\(User: ([^)]*)\)/.exec(document.getElementById('footer').textContent​​​​​​​​)[1];
if(allowed_users.indexOf(user) === -1) // user not in allowed_users array, disable priority
{
    var oldInput = document.getElementsByName('prio')[0];
    oldInput.setAttribute('disabled', 'disabled');
}

答案 2 :(得分:1)

在Firefox 2.0中运行:

//--- Make sure this list of names is all uppercase.
var usersWhoCanSetPriority = ['JOHN', 'LUKE', 'JEFF', 'MAX', 'ANDY'];

var bDisablePrio    = true;
var tdNodes         = document.getElementsByTagName ("TD");
for (var J = tdNodes.length - 1;  J >= 0;  --J) {
    var tdNode      = tdNodes[J];
    if (tdNode.className == "user") {
        var userName        = tdNode.textContent.replace (
            /^(?:.|\n|\r)+\(User:\s+([^)]+)\)(?:.|\n|\r)+$/i, "$1"
        ).toUpperCase ();

        if (usersWhoCanSetPriority.indexOf (userName) > -1) {
            bDisablePrio    = false;
        }
    }
}

if (bDisablePrio) {
    var oldInput = document.getElementsByName ("prio");
    oldInput[0].setAttribute ("disabled", "disabled");
}

请参阅the updated Fiddle