3

この問題は今日私に来ました。私は多くのJSPを使用するWebベース(Struts 2)プロジェクトで作業しており、ほとんどのinput, select, table要素は属性aのみで定義されており、次のように設定されていません。nameid

<input name="myname" class="myclass" value="" type="text"/>

残念ながら、これらのフィールドには多くのjavascript検証があり、それらのほとんどを残す前にコードを読むことができる限り、実際には。を含む要素を参照していることを除いて、これまでのところ良好document.getElementByIdです。

ここでの落とし穴は、これがIE-6およびIE-7とのみ互換性のある古いアプリケーション(実際にはそれほど古いものではない)であるということです(IEが実際に要素を見つけるのはname属性が、私はそれが何かをしなければならないと思います)。他のすべてのブラウザが文句を言ったり泣いたりするのは当然のことです。

そこで、私は簡単な解決策を考え出そうとしています。HTMLを修正するためではなく、属性input, select, tablea持つ要素を定義するすべてのJSPを検索します。nameid

私の古き良き友人http://rubular.comを使用して、私は次のことを思いついた:

/<(?:(input|select|a|table))\s+((?!id).)*>

これにより、参照されているすべての要素が。なしでキャッチされますidnameしかし、実際に一致するものだけを主張するにはどうすればよいですか?

ああ、もう一つの重要なポイント。要素の定義は1行であるため、次のようなものがない可能性が最も高くなります。

<input name="..."
       class="..."/>
4

4 に答える 4

6

これを試して:

<(?:input|select|a|table)\s+(?=[^>]*\bname\s*=)(?![^>]*\bid\s*=)[^>]*>

説明:

<                           "<"
(?:input|select|a|table)    One of "input", "select", "a", "table"
\s+                         Whitespace
(?=                         Positive lookahead
[^>]*                           Anything up to but excluding ">"
\b                              Word boundary
name                            "name"
\s*                             Possible whitespace
=                               "="
)
(?!                         Negative lookahead
[^>]*                           Anything up to but excluding ">"
\b                              Word boundary
id                              "id"
\s*                             Possible whitespace
=                               "="
)
[^>]*                       Anything up to but excluding ">"
>                           ">"
于 2012-11-08T02:45:57.823 に答える
2

免責事項:

誰もがHTMLを解析するために正規表現を使用しないようにあなたに言うでしょう、そして彼らは正しいです。とは言うものの、次の正規表現ソリューションは、1回限りのタスクに対してかなり適切な仕事をするはずです(100%の信頼性が問題にならない場合)。

ある属性を持ち、別の属性を持たないタグと一致する正規表現:

次のテスト済みのPHPスクリプトは、(完全にコメント化された)正規表現を使用して、、、、および属性はあるが属性がない要素の開始タグを照合しINPUTます。スクリプトは、既存の属性と同じ新しい属性を各開始タグに挿入します。SELECTTABLEANAMEIDIDNAME

<?php // test.php Rev:20121107_2100
$re = '%
    # Match HTML 4.01 element start tags with NAME but no ID attrib.
    (                      # $1: Everything up to tag close delimiter.
      <                    # Start tag open delimiter.
      (?:input|select|table|a)\b  # Element name.
      (?:                  # Zero or more attributes before NAME.
        \s+                # Attributes are separated by whitespace.
        (?!name\b|id\b)    # Only non-NAME, non-ID before NAME attrib.
        [A-Za-z][\w\-:.]*  # Attribute name is required.
        (?:                # Attribute value is optional.
          \s*=\s*          # Name and value separated by =
          (?:              # Group for value alternatives.
            "[^"]*"        # Either a double-quoted string,
          | \'[^\']*\'     # or a single-quoted string,
          | [\w\-:.]+      # or a non-quoted string.
          )                # End group of value alternatives.
        )?                 # Attribute value is optional.
      )*                   # Zero or more attributes before NAME.
      \s+                  # NAME attribute is separated by whitespace.
      name                 # NAME attribute name is required.
      \s*=\s*              # Name and value separated by =
      (                    # $2: NAME value.
        "[^"]*"            # Either a double-quoted string,
      | \'[^\']*\'         # or a single-quoted string,
      | [\w\-:.]+          # or a non-quoted string.
      )                    # $2: NAME value.
      (?:                  # Zero or more attributes after NAME.
        \s+                # Attributes are separated by whitespace.
        (?!id\b)           # Only non-ID attribs after NAME attrib.
        [A-Za-z][\w\-:.]*  # Attribute name is required.
        (?:                # Attribute value is optional.
          \s*=\s*          # Name and value separated by =
          (?:              # Group for value alternatives.
            "[^"]*"        # Either a double-quoted string,
          | \'[^\']*\'     # or a single-quoted string,
          | [\w\-:.]+      # or a non-quoted string.
          )                # End group of value alternatives.
        )?                 # Attribute value is optional.
      )*                   # Zero or more attributes after NAME.
    )                      # $1: Everything up to close delimiter.
    # Insert missing ID attribute here...
    (\s*/?>)               # $3: Start tag close delimiter.
    %ix';
$html = file_get_contents('testdata.html');
$html = preg_replace($re, "$1 id=$2$3", $html);
file_put_contents('testdata_out.html', $html);
?>
于 2012-11-08T05:30:27.543 に答える
0

javascriptでgetElementByIdを使用する場合、idで使用されているのと同じ名前の要素が存在する場合、Internet Explorerで機能しますが、他のすべてのブラウザー(Firefox、Chrome、Safariなど)では機能しません。

次のコードで削除できます。

function includeIdIfNotExist(element) {
    var id = element.getAttribute('id');
    var name = element.getAttribute('name');
    if (name && !id) {
        element.id = name;
    }
}
function addMissingId() {
    var elementsToAddId = ['input', 'select'];
    for (var j = 0; j < elementsToAddId.length; j++) {
        var inputElements = document.getElementsByTagName(elementsToAddId[j]);
        for (var i = 0; i < inputElements.length; i++) {
            includeIdIfNotExist(inputElements[i]);
        }
    }
}
document.onload = addMissingId();
于 2015-12-01T09:14:49.693 に答える
0

名前はあるがidはない要素を検索し、idを名前と同じに設定する場合は、次のように検索と置換を行うことができます。

探す:

(<(?:input|select|table|form|textarea)\s+)(?=[^>]*\bname\s*="(\w+)")((?![^>]*\bid\s*=)[^>]*>)

input、select、table、form、textareaで動作するように作られています。input | select | table | form|textarea部分からhtmlタグを追加または削除できます。また、要素にIDがあるかどうかもチェックします

と置換する:

$1id="$2" $3

これにより、前に選択したhtmlタグにid = "[nameValue]"が追加されます。このタグには、名前はありますがIDはありません。

それが役に立てば幸い!

于 2018-01-16T15:37:37.317 に答える