1

在 Java 等语言或 Qt for C++ 等 GUI 框架中,可以获得用户无法更改但程序可以根据满足某些条件进行修改的某些文本块(例如标签小部件)的句柄。我希望能够从一些 JavaScript 代码中在 HTML 网页上做同样的事情。

例如,考虑一个用于输入用户凭据的网页。如果凭据无效,我想在当前网页上显示一条消息,而无需加载全新的页面。

我已经使用 HTML 文本框或 textarea 使其工作,设置为禁用,只读并进行一些显示样式更改(通过 CSS)。更改会导致一些 JavScript 代码运行,这可能会导致这些文本框或文本区域的值字段发生更改。虽然这行得通,但它似乎并不正确。有没有更正统的方法来实现这一点?

4

3 回答 3

1

Sure. There are a few libraries to handle this.

You may be asking for form validation. If so, try jQuery and jQuery's validate extension library: demo

Or you may be asking for a more generic-use observer pattern. If so, try one of the many MVVM/MVC libraries for JavaScript such as backbone.js or knockout.js (also ember, agility, angular, and spine): jsfiddle

edit: also note that if your need is just standard form validation, you can accomplish it in jQuery validate without any code to speak of - just add properties directly on the HTML elements themselves indicating what the validation rules are. Unfortunately, HTML5 data attributes weren't around when it was written, so you apply the validation rules as CSS classes.

edit 2: also note that jQuery validate out-of-the-box supports remote validation, such as the credentials or username-already-exists scenario: demo or documentation

于 2012-09-01T05:22:00.593 回答
1

Use jQuery's .submit(), using this you can Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

Example:

$("form").submit(function() {
      if ($("input:first").val() == "correct") {
        $("span").text("Validated...").show();
        return true;
      }
      $("span").text("Not valid!").show().fadeOut(1000);
      return false;
    });

You can also use jQuery's .toggle() to show/hide any div.

Read this W3C article for better understanding of recommendation by W3, Providing client-side validation and adding error text via the DOM (slightly outdated)

于 2012-09-01T05:25:30.073 回答
0

你应该试试jQuery的.change();

假设您的 HTML 输入有一个 ID:

<input type='text' id='idOfTheField' name='email'>

你应该试试:

$('#idOfTheField').change(function(){

  //Do stuff with the value.
  //Wich is $('#idOfTheField').value() by the way.

});

要使用网络服务器操作数据,您必须执行 AJAX 调用,如下所示:

$.ajax({
  url: "parse.php",
  data: {
      email:$('#idOfTheField').value()
  }
}).done(function() { 
  // Add the CSS class ".valid" that makes the text field green, for example.
  $('#idOfTheField').addClass("valid"); 
});
于 2012-09-01T05:13:57.340 回答