情况:我已经从SmartRecruiters API请求了JSON数据并将其添加到我的布局中。因为工作描述很长,我想限制p
到x#字符内的字符数。经过研究,我与.text()
合作并得出结论:
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");
});
}
});
答案 0 :(得分:1)
无需:
var desc = $('.desc')
desc.each(function() {
$(this).text(desc.text().substring(0,250) + '...');
console.log("work");
});
只是做:
jobDetail.textContent = jobDesc.substr(0, 250) + "..."