使用find函数获取点击Apply按钮对应职位的.postingTitle值失败求助
It looks like the main issues with your code are two key mistakes: using .val() on a non-form element, and not targeting the specific clicked button correctly. Let's break down the fixes step by step.
Why Your Current Code Isn't Working
.postingTitleis an<h3>element, not a form input (like<input>or<textarea>). The.val()method only retrieves values from form elements—for getting text content from regular HTML elements, you need to use.text()instead.- Using
$('.applyButton')inside the click handler will select all buttons with that class, not just the one the user clicked. This can lead to unexpected results when multiple job postings exist on the page.
Corrected JavaScript Code
var jobTitle = ''; // Ensure code runs after DOM is fully loaded $(document).ready(function() { $('.applyButton').on('click', function (event) { // Use $(this) to target the specific button that was clicked // Traverse up to the closest parent .postingInner, then find the associated .postingTitle jobTitle = $(this).closest('.postingInner').find('.postingTitle').text().trim(); $('#jobTitle').html(jobTitle); console.log(jobTitle); }); });
Key Improvements Explained
$(this): References the exact button that was clicked, ensuring we're looking for the job title in the correct posting container..closest('.postingInner'): Efficiently travels up the DOM tree to find the nearest parent element wrapping both the title and button, instead ofparents().find()which checks all parent elements (less efficient and prone to targeting unintended elements)..text().trim(): Retrieves the text content of the<h3>and removes any extra whitespace, giving you a clean job title string.$(document).ready(): Makes sure your jQuery code runs only after all HTML elements have been rendered on the page, preventing cases where the buttons might not exist yet when the code initializes.
Additional Notes
- Double-check that jQuery is properly included in your page before this script runs.
- If you're dynamically loading job postings (e.g., via AJAX), use event delegation instead to ensure the click event works for newly added elements:
$(document).on('click', '.applyButton', function(event) { jobTitle = $(this).closest('.postingInner').find('.postingTitle').text().trim(); $('#jobTitle').html(jobTitle); console.log(jobTitle); });
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

