0
情況:我已經從SmartRecruiters API請求了JSON數據並將其附加到我的佈局中。由於工作描述太長,我想將p
中的字符數限制爲x個字符。研究後,我曾與.text()
,所以決定這一點:.text()返回JSON成功函數中的重複數據
var desc = $('.desc')
desc.text(desc.text().substring(0,250) + '...');
console.log("work");
代碼成功地限制的字符數,但返回重複JSON數據在說明每個崗位。
我已經試過:
- 我想它有一些東西需要與被包含在
showDetails
函數中的代碼,所以我從功能刪除,並把它放在「外」。它不起作用。 - 由於我設置
p
與類.desc
,我想我將不得不使用$.each
。
我寫道:
var desc = $('.desc')
desc.each(function() {
$(this).text(desc.text().substring(0,250) + '...');
console.log("work");
});
返回重複數據。
- 我想也許是因爲它是一個班,所以我切換到
#desc
。更改爲jobDetail.setAttribute('class', 'desc')
,並調用$('#desc')
它的工作將隨機限制只有幾個p
但不是全部。
問題:我怎樣才能正確地限制我的p
內容長度和我的JSON函數中添加一個省略號?
完整代碼:
$(document).ready(function() {
// Create variable to append postings to
var postingsContainer = document.querySelector('div.job-container');
// Creates postings JSON request
$.getJSON('https://api.smartrecruiters.com/v1/companies/SynchronyGroup/postings', function (postings) {
// Check to see if data is being pulled
//console.log(postings);
showJobs(postings);
});
// Function that pulls json data and populates careers section
function showJobs(jsonObj) {
// Variable that holds job postings json data
var jobs = jsonObj['content']
// Loop to create open position elements
for (var i = 0; i < jobs.length; i++) {
// Creates Column for job postings
var jobPosting = document.createElement('div');
jobPosting.setAttribute('class', 'col-12 col-md-6 col-lg-4 my-5 job-posting');
// Creates Job Title
var jobH5 = document.createElement('h5');
jobH5.textContent = jobs[i].name;
jobPosting.appendChild(jobH5);
postingsContainer.appendChild(jobPosting);
// Store job post IDs in var
var jobId = jobs[i].ref;
//
//
// IIFE
(function (jobPosting) {
// Creates post 2nd ID JSON request
$.getJSON(jobId, function (data) {
// Check to see if data is being pulled
console.log(data);
showDetails(data, jobPosting);
})
}(jobPosting));
}
}
//Function for posting description and apply url
function showDetails(data, jobPosting) {
// Creates Company Desc. and Apply Link
var jobDetail = document.createElement('p');
var jobApply = document.createElement('a');
// Pulls job description data and strips HTML Markup
jobDesc = data.jobAd.sections.jobDescription.text.replace(/<\/?[^>]+>/gi, '');
jobDetail.setAttribute('class', 'desc')
jobDetail.textContent = jobDesc;
jobApply.setAttribute('href', data.applyUrl);
jobApply.setAttribute('class', 'btn-primary');
jobApply.setAttribute('target', '_blank');
jobApply.textContent = 'Apply for Position'
jobPosting.appendChild(jobDetail);
jobPosting.appendChild(jobApply);
var desc = $('.desc')
desc.each(function() {
$(this).text(desc.text().substring(0,250) + '...');
console.log("work");
});
}
});
@Andreas哇...這麼簡單吧好了,它的工作。謝謝你的快速反應。 – WeebleWobb