如何使用jQuery更改占位符文本?

2021年3月15日09:40:05 发表评论 1,206 次浏览

占位符文本是用户输入的文本输出。就像在HTML中一样, 我们使用"名称"作为输入字段, 并在该空间内放置文本, 即输入你的姓名。如下图所示:

名称:

因此, 我们需要一个按钮或某个事件来将占位符文本更改为其他文本。为此, 我们有以下两种方法:

方法1:在这种方法中, 我们将使用attr()方法。的attr()方法用于设置或返回选定元素的指定属性。它带有两个参数, 第一个是要设置的属性, 第二个是要更改为的属性的值。

的"占位符"属性控制将在输入区域中显示为占位符的文本。此属性作为第一个参数传递给attr()方法。将要设置的必需文本作为第二个参数传递。这会将元素的占位符文本更改为新文本。

语法:$('selectedTextarea')。attr('placeholder', 'Placeholder text');

例子:

<!DOCTYPE html>
< html >
< head >
     < title >
         Changing Placeholder text
     </ title >
     < style >
         body {
             text-align: center;
         }
     </ style >
</ head >
  
< body >
     < h1 style = "color: green;" >
      lsbin
     </ h1 >
     < b >
      Changing Placeholder text
     </ b >
     < p >
       Click the button to change placeholder 
       of the textarea.
     </ p >
     < textarea id = "area1" placeholder = "Default Text" ></ textarea >
     < br >
     < button onclick = "changePlaceholder()" >
         Change Placeholder
     </ button >
  
     < script src = "https://code.jquery.com/jquery-3.4.1.min.js" >
     </ script >
     < script type = "text/javascript" >
         function changePlaceholder() {
             $('#area1').attr('placeholder', 'This is a new placeholder');
         }
     </ script >
</ body >
  
</ html >

输出如下:

在单击按钮之前:

之前的属性

单击按钮后:

之后

方法2:使用占位符属性。 "占位符"属性用于获取或设置输入文本的占位符。这可用于将占位符文本更改为新文本。首先使用jQuery选择器选择元素。然后可以将新的占位符文本分配给元素的占位符属性。这会将元素的占位符文本更改为新文本。

语法:selectedTextarea = $('selectedTextarea')[0]; selectedTextarea.placeholder ="占位符文本";

例子:

<!DOCTYPE html>
< html >
  
< head >
     < title >
         Changing Placeholder text
     </ title >
     < style >
         body {
             text-align: center;
         }
     </ style >
</ head >
  
< body >
     < h1 style = "color: green;" >
      lsbin
     </ h1 >
     < b >
      Changing Placeholder text
     </ b >
     < p >
      Click the button to change placeholder 
      of the textarea.
     </ p >
     < textarea id = "area1" placeholder = "Default Text" ></ textarea >
     < br >
     < button onclick = "changePlaceholder()" >
         Change Placeholder
     </ button >
  
     < script src = "https://code.jquery.com/jquery-3.4.1.min.js" >
     </ script >
     < script type = "text/javascript" >
         function changePlaceholder() {
             selectedTextarea = $('#area1')[0];
  
             selectedTextarea.placeholder =
                 "This is a new placeholder";
         }
     </ script >
</ body >
  
</ html >

输出如下:

在单击按钮之前:

之前的属性

单击按钮后:

之后

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: