简体   繁体   English

用jQuery缩写数据库输出

[英]abbreviate database output with jquery

I am looking for a way to limit the amount of characters displayed in a heading using jquery. 我正在寻找一种方法来限制使用jquery的标题中显示的字符数。 Essentially the heading is retreived from the database but I only want the results to display on one line of a set width so would like to limit the output or abbreviate it to stop the images below being pushed too far down. 从本质上来说,标题是从数据库中检索出来的,但是我只希望结果显示在设置宽度的一行上,以便限制输出或缩写以阻止将下面的图像推得太低。

The following Live example should show everything that I mean, scroll down a bit and you will see images titles that are 2 or 3 lines long. 下面的Live示例应显示我的意思,向下滚动一点,您将看到2或3行长的图像标题。

Hope someone can help!!!! 希望有人可以帮助!!!

Dan, I'm a bit confused about what you're looking for, but it sounds like you want some code to truncate the character length of a certain field. 丹,对于您要查找的内容我有些困惑,但这听起来像是您想要一些代码来截断某个字段的字符长度。 I noticed that you tagged this question PHP -- it'd probably be better to handle it server-side. 我注意到您标记了这个问题PHP-在服务器端处理它可能会更好。 However, if you're set on using Jquery, there's probably an easy way to do it. 但是,如果您打算使用Jquery,则可能有一种简单的方法。

The key thing to figure out is, what pattern are you going to use to identify the field tags within the page (ie. what kind of jquery selector will you write to select the tags you want)? 要弄清楚的关键是,您将使用哪种模式来识别页面内的字段标签(即,您将编写哪种类型的jquery选择器来选择所需的标签)? Once that's down, javascript's .slice() function will achieve what you want. 一旦关闭,javascript的.slice()函数将实现您想要的。

So here's an example. 所以这是一个例子。 Based on the page you linked, I'm going to say we could select your field output by selecting any span tag that is a direct child of an anchor tag that is a direct child of a list item. 根据您链接的页面,我要说的是,我们可以通过选择任何span标签来选择您的字段输出,这些span标签是锚标签的直接子标签,而该锚标签是列表项的直接子标签。

$('li > a > span')

Then from there we can grab the contents of the span, check the width, and truncate if we need to. 然后从那里我们可以获取跨度的内容,检查宽度,并在需要时截断。

(untested, but gives the idea) (未经测试,但给出了主意)

<script type="text/javascript">

    var MAX_TITLE_LENGTH = 75;

    // on page load...
    $(function() {
        truncateImageTitles();      
    });

    function truncateImageTitles() {
        $('li > a > span').each(
            if (this.text().length > MAX_TITLE_LENGTH)
                this.text(this.text().slice(0,MAX_TITLE_LENGTH));
        );
    }

</script>

Trim with PHP would work, as T. Stone said, but you'd have to figure out if you want to trim the front end of a title or the back end. 就像T. Stone所说的那样,用PHP进行修剪是可以的,但是您必须弄清楚是要修剪标题的前端还是后端。 Lots of examples. 很多例子。 I use trim with titles on my own wordpress site. 我在自己的wordpress网站上使用带有标题的trim。 This trims the first 13 characters from a post title, in place of the_title. 这会修剪帖子标题的前13个字符,代替the_title。

<?php $mytitle = get_the_title(); $mytitle = substr($mytitle,13); echo $mytitle; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM