📜  p5.js 元素 id() 方法

📅  最后修改于: 2022-05-13 01:56:39.882000             🧑  作者: Mango

p5.js 元素 id() 方法

p5.js 中 p5.Element 的id()方法用于设置或返回元素的 ID。如果没有指定 ID 作为参数,则返回元素的当前 ID。页面上只有一个元素可以具有指定的特定 ID。

句法:

id( id )

参数:此函数接受如上所述和下文所述的单个参数。

  • id:它是一个字符串,表示元素的ID。

示例 1:下面的示例说明了 p5.js 中的id()方法。

Javascript
function setup() {
  createCanvas(550, 300);
  textSize(18);
  
  text("Click on the button to create a new " +
       "element with the given ID", 20, 20);
  
  setBtn = 
    createButton("Create new Element with ID");
  setBtn.position(30, 40);
  setBtn.mouseClicked(createNewElement);
  
  setBtn = 
    createButton("Show Last Element ID");
  setBtn.position(300, 40);
  setBtn.mouseClicked(showID);
  
  id_name = createInput('tmpID');
  id_name.position(30, 80);
}
  
function createNewElement() {
  clear();
  
  // Create a new p5.Element
  tmpElement = createElement("p");
  
  // Get the ID to set
  let idToSet = id_name.value();
  
  // Set the ID of the element
  tmpElement.id(idToSet);
  
  text("New element created with ID: " +
       idToSet, 30, 120);
  
  text("Click on the button to create a new " +
       "element with the given ID", 20, 20);
}
  
function showID() {
  clear();
  
  // Get the ID of the element
  let setID = tmpElement.id();
  
  // Display the ID
  text("The ID of the last element is: " + 
       setID, 30, 120);
  
  text("Click on the button to create a new " +
       "element with the given ID", 20, 20);
}


Javascript
function setup() {
  
  // Create a new canvas
  canv = createCanvas(550, 300);
  
  // Set the ID of the canvas
  canv.id("newCanvas");
  
  textSize(18);
  text("Click on the button to show the ID " +
       "of the canvas element", 20, 20);
  
  setBtn = 
    createButton("Show ID of the canvas");
  setBtn.position(30, 40);
  setBtn.mouseClicked(showID);
}
  
function showID() {
  clear();
  
  // Get the ID of the element
  let setID = canv.id();
  
  // Display the ID
  text("The ID of the canvas is: " +
       setID, 20, 80);
  
  text("Click on the button to show the ID " +
       "of the canvas element", 20, 20);
}


输出:

示例 2:

Javascript

function setup() {
  
  // Create a new canvas
  canv = createCanvas(550, 300);
  
  // Set the ID of the canvas
  canv.id("newCanvas");
  
  textSize(18);
  text("Click on the button to show the ID " +
       "of the canvas element", 20, 20);
  
  setBtn = 
    createButton("Show ID of the canvas");
  setBtn.position(30, 40);
  setBtn.mouseClicked(showID);
}
  
function showID() {
  clear();
  
  // Get the ID of the element
  let setID = canv.id();
  
  // Display the ID
  text("The ID of the canvas is: " +
       setID, 20, 80);
  
  text("Click on the button to show the ID " +
       "of the canvas element", 20, 20);
}

输出:

在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.Element/id