Причины, почему селекторы на основе id не работают
Решения
$(document).ready();
.bind()
для jQuery. В старых версиях jQuery для этого было .live()
. Вы также захотите добавить к нему логарифмическую функцию. (взято из tagadelic, моего модуля Drupal для создания облаков тегов http://drupal.org/project/tagadelic ):
db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');
$steps = 6;
$tags = array();
$min = 1e9;
$max = -1e9;
while ($tag = db_fetch_object($result)) {
$tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it
$tag->count = log($tag->count);
$min = min($min, $tag->count);
$max = max($max, $tag->count);
$tags[$tag->tid] = $tag;
}
// Note: we need to ensure the range is slightly too large to make sure even
// the largest element is rounded down.
$range = max(.01, $max - $min) * 1.0001;
foreach ($tags as $key => $value) {
$tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range);
}
Затем в вашем представлении или шаблоне:
foreach ($tags as $tag) {
$output .= "<h$tag->weight>$tag->name</h$tag->weight>"
}
Первое, что пришло на ум...
$artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE");
$count = array(5,3,9,1,1,3);
$highest = max($count);
for (int $x = 0; $x < count($artist); $x++)
{
$normalized = $count[$x] / $highest;
$heading = ceil($normalized * 6); // 6 heading types
echo "<h".$heading.">".$artist[$x]."</h".$heading.">";
}
Возможно, это - маленький академик и вне темы но hX
теги являются, вероятно, не лучшим выбором для облака тегов по причинам структуры документа и всей такой вещи.
, Возможно span
с или ol
с соответствующими атрибутами класса (плюс некоторый CSS)?
Использовали этот отрывок некоторое время, кредитом является prism-perfect.net. Не использует теги H хотя
<div id="tags">
<div class="title">Popular Searches</div>
<?php
// Snippet taken from [prism-perfect.net]
include "/path/to/public_html/search/settings/database.php";
include "/path/to/public_html/search/settings/conf.php";
$query = "SELECT query AS tag, COUNT(*) AS quantity
FROM sphider_query_log
WHERE results > 0
GROUP BY query
ORDER BY query ASC
LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$tags[$row['tag']] = $row['quantity'];
}
// change these font sizes if you will
$max_size = 30; // max font size in %
$min_size = 11; // min font size in %
// get the largest and smallest array values
$max_qty = max(array_values($tags));
$min_qty = min(array_values($tags));
// find the range of values
$spread = $max_qty - $min_qty;
if (0 == $spread) { // we don't want to divide by zero
$spread = 1;
}
// determine the font-size increment
// this is the increase per tag quantity (times used)
$step = ($max_size - $min_size)/($spread);
// loop through our tag array
foreach ($tags as $key => $value) {
// calculate CSS font-size
// find the $value in excess of $min_qty
// multiply by the font-size increment ($size)
// and add the $min_size set above
$size = $min_size + (($value - $min_qty) * $step);
// uncomment if you want sizes in whole %:
// $size = ceil($size);
// you'll need to put the link destination in place of the /search/search.php...
// (assuming your tag links to some sort of details page)
echo '<a href="/search/search.php?query='.$key.'&search=1" style="font-size: '.$size.'px"';
// perhaps adjust this title attribute for the things that are tagged
echo ' title="'.$value.' things tagged with '.$key.'"';
echo '>'.$key.'</a> ';
// notice the space at the end of the link
}
?>
</div>
@Ryan
Это корректно, но он на самом деле делает теги с наименьшим количеством числа, больше. Этот код был протестирован:
$artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE");
$count = array(5,3,9,1,1,3);
$highest = max($count);
for ($x = 0; $x < count($artist); $x++) {
$normalized = ($highest - $count[$x]+1) / $highest;
$heading = ceil($normalized * 6); // 6 heading types
echo "<h$heading>{$artist[$x]}</h$heading>";
}
Как помощник в направляющих:
def tag_cloud (strings, counts)
max = counts.max
strings.map { |a| "<span style='font-size:#{((counts[strings.index(a)] * 4.0)/max).ceil}em'>#{a}</span> " }
end
Вызов это от представления:
<%= tag_cloud($artists, $counts) %>
Это производит <span style='font-size:_em'>
элементы в массиве, который будет преобразован в строку в представлении для окончательного рендеринга как так:
<span style='font-size:3em'>the roots</span>
<span style='font-size:2em'>michael jackson</span>
<span style='font-size:4em'>billy idol</span>
<span style='font-size:1em'>more</span>
<span style='font-size:1em'>and more</span>
<span style='font-size:2em'>and_YET_MORE</span>
было бы лучше иметь class
атрибут и сослаться на классы в таблице стилей, как упомянуто Brendan выше. Намного лучше, чем использование h1-h6
семантически и существует меньше багажа стиля с <span>
.
Этот метод для фанатиков SQL/PostgreSQL
. Он выполняет всю работу в базе данных и печатает текст с "пропущенной" ссылкой. Он использует Doctrine ORM
только для вызова sql, я не использую объекты.
Предположим, у нас есть 10 размеров:
public function getAllForTagCloud($fontSizes = 10)
{
$sql = sprintf("SELECT count(tag) as tagcount,tag,slug,
floor((count(*) * %d )/(select max(t) from
(select count(tag) as t from magazine_tag group by tag) t)::numeric(6,2))
as ranking
from magazine_tag mt group by tag,slug", $fontSizes);
$q = Doctrine_Manager::getInstance()->getCurrentConnection();
return $q->execute($sql);
}
тогда вы выводите их с некоторым классом CSS, от .tagranking10 (лучший) до .tagranking1 (худший):
<?php foreach ($allTags as $tag): ?>
<span class="<?php echo 'tagrank'.$tag['ranking'] ?>">
<?php echo sprintf('<a rel="tag" href="/search/by/tag/%s">%s</a>',
$tag['slug'], $tag['tag']
); ?>
</span>
<?php endforeach; ?>
и это CSS
:
/* put your size of choice */
.tagrank1{font-size: 0.3em;}
.tagrank2{font-size: 0.4em;}
.tagrank3{font-size: 0.5em;}
/* go on till tagrank10 */
Этот метод выводит все теги. Если у вас их много, вы, вероятно, не хотите, чтобы ваше облако тегов превратилось в бурю тегов. В этом случае вы добавите к SQL-запросу предложение HAVING TO
:
-- minimum tag count is 8 --
HAVING count(tag) > 7
Это все