You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery获取点击段落中的firstName与lastName值并展示

Solution: Extract First & Last Name on Paragraph Click

Hey there! Let's fix your issue where you can't pull out the first and last name separately when clicking a contact paragraph. We've got two reliable approaches to solve this—let's dive in:

Storing the first and last name directly in HTML data-* attributes is the most robust method. This way, we don't have to parse text (which can break if the text format changes later).

Step 1: Update the Contact HTML Creation

When appending the new contact to the list, add data-first and data-last attributes to the paragraph tag to store the raw values:

$("ul#contacts").append("<li class='contact'>" + "<p class='para' data-first='"+newContact.firstName+"' data-last='"+newContact.lastName+"'>" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");

Step 2: Write the Click Event Handler

Now, when the paragraph is clicked, we can directly retrieve the values from the data attributes without parsing:

$('#contacts').on('click', 'p.para', function (e) {
  // Grab values from the data attributes
  const firstName = $(this).data('first');
  const lastName = $(this).data('last');

  // Update the display div with the extracted names
  $("#show-contact").show();
  $("#show-contact h2").text(`${firstName} ${lastName}`);
  $(".first-name").text(firstName);
  $(".last-name").text(lastName);
});

Approach 2: Parse Text with Regular Expressions

If you prefer not to modify the HTML structure, you can extract the names from the paragraph's text using regex. This works as long as the text format stays consistent.

Click Event Handler for Text Parsing

$('#contacts').on('click', 'p.para', function (e) {
  const paragraphText = $(this).text();
  
  // Use regex to match the first and last name values
  const firstNameMatch = paragraphText.match(/First Name: (\S+)/);
  const lastNameMatch = paragraphText.match(/Last Name: (\S+)/);
  
  // Extract the matches (fallback to empty string if no match is found)
  const firstName = firstNameMatch ? firstNameMatch[1] : '';
  const lastName = lastNameMatch ? lastNameMatch[1] : '';

  // Update the display div
  $("#show-contact").show();
  $("#show-contact h2").text(`${firstName} ${lastName}`);
  $(".first-name").text(firstName);
  $(".last-name").text(lastName);
});

Full Modified Code

Here's the complete working code with Approach 1 implemented (the more reliable option):

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <h1 id="haha">Address book</h1>
  <div class="row">
    <div class="col-md-6">
      <h2>Add a contact:</h2>
      <form id="new-contact">
        <div class="form-group">
          <label for="new-first-name">First name</label>
          <input type="text" class="form-control" id="new-first-name">
        </div>
        <div class="form-group">
          <label for="new-last-name">Last name</label>
          <input type="text" class="form-control" id="new-last-name">
        </div>
        <button id="delBtn" class="btn">Delete All</button> <!-- Updated text to match functionality -->
        <button id="save" class="btn">Save</button>
      </form>
      <h2>Contacts:</h2>
      <ul id="contacts">
      </ul>
    </div>
    <div class="col-md-6">
      <div id="show-contact">
        <h2></h2>
        <p>First name: <span class="first-name"></span></p>
        <p>Last name: <span class="last-name"></span></p>
      </div>
    </div>
  </div>
</div>

JavaScript

function Contact(first, last) { 
  this.firstName = first; 
  this.lastName = last; 
}

$(document).ready(function() {
  let a_contacts = [];

  $("#delBtn").click(function() {
    $("li").remove();
  });

  $("#save").click(function(event) {
    event.preventDefault()
    var inputtedFirstName = $("input#new-first-name").val();
    var inputtedLastName = $("input#new-last-name").val();
    var newContact = new Contact(inputtedFirstName, inputtedLastName);
    
    // Append contact with data attributes to store raw name values
    $("ul#contacts").append("<li class='contact'>" + "<p class='para' data-first='"+newContact.firstName+"' data-last='"+newContact.lastName+"'>" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
    
    a_contacts.push(newContact);
    $("input#new-first-name").val("");
    $("input#new-last-name").val("");
  });

  // Click handler to extract and display names
  $('#contacts').on('click', 'p.para', function (e) {
    const firstName = $(this).data('first');
    const lastName = $(this).data('last');
    
    $("#show-contact").show();
    $("#show-contact h2").text(`${firstName} ${lastName}`);
    $(".first-name").text(firstName);
    $(".last-name").text(lastName);
  });

  $('#contacts').on('click', '.del', function(event) {
    $(event.target).parent().remove()
  });
});

Quick Notes

  • I updated the #delBtn text to "Delete All" since its functionality is removing all list items—this is just a usability tweak, feel free to change it back if needed.
  • Approach 1 is better long-term because it decouples the data from the display text. If you ever change how the contact text is formatted (e.g., "Name: John Doe"), the data attributes will still work, whereas the regex would need updating.

内容的提问来源于stack exchange,提问作者Happy Coconut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:40:22