안녕하세요.
사이트에 등록된 매장의 리스트를 페이지 로드할 때마다 출력되는 순서를 랜덤으로 출력되게 하려고 합니다
지식이 많이 없어서 챗GPT의 도움으로 셔플 함수를 스크립트에 추가해봤는데 작동이 안 되어서 이렇게 또 질문을 하게 되었네요^^;;
아래는 리스트 페이지와 자바 코드입니다.
html
Copy
<div id="store_list_sch">
<div class="store_find">
<ul class="find_ul">
<li>
<button class="ab" onClick="toggle_fade('popup_loca',this);">
<img src="<?=G5_THEME_IMG_URL?>/icon_map.svg" alt="">
<span id="loca_txt"><?php echo (!$sido ? '전체 지역' : fnSidoTo2Letter($sido).' > 전체'); ?></span>
</button>
</li>
<li>
<button class="ab" onClick="toggle_fade('popup_theme',this);">
<img src="<?=G5_THEME_IMG_URL?>/icon_widgets.svg" alt="">
<span id="theme_txt">테마 선택</span>
</button>
</li>
</ul>
<form method="get" onsubmit="return fnStoreSearchSubmit()">
<div class="find_form">
<input type="hidden" name="sido" id="sido" value="<?=$sido?>">
<input type="hidden" name="sigungu" id="sigungu" value="<?=$sigungu?>">
<input type="hidden" name="theme" id="theme" value="<?=$theme?>">
<input class="inp" type="text" name="stx" id="stx" placeholder="검색어를 입력해 주세요">
<button class="ab"><img src="<?=G5_THEME_IMG_URL?>/icon_sch_b.svg" alt=""></button>
</div>
</form>
</div>
<div id="store_list_wrap">
</div>
</div>
자바스크립트
Copy
<script>
$(document).ready(function() {
// 페이지 로드 시 실행
shuffleList();
$("#themeall").click(function() {
if($("#themeall").is(":checked")) $("input[name=theme_c]").prop("checked", true);
else $("input[name=theme_c]").prop("checked", false);
});
$("input[name=theme_c]").click(function() {
var total = $("input[name=theme_c]").length;
var checked = $("input[name=theme_c]:checked").length;
if(total != checked) $("#themeall").prop("checked", false);
else $("#themeall").prop("checked", true);
});
$("input[name=sido_c]").change(function() {
fnSelSido2($(this).val(), '');
});
});
function shuffleList() {
var storeList = $("#store_list_wrap");
var items = storeList.children();
while (items.length) {
storeList.append(items.splice(Math.floor(Math.random() * items.length), 1)[0]);
}
}
function fnThemeEnter(){
var theme = '';
var theme_txt = '';
var more = 0;
$("input[name=theme_c]:checked").each(function(){
if(theme != ''){
theme += ',';
more++;
}
theme += $(this).val();
if(more < 1){
theme_txt += $(this).val();
}
});
if(more > 0){
theme_txt += " 외 "+more+"개";
}
if(theme_txt == ''){
theme_txt = '테마 선택';
}
$("#theme").val(theme);
$("#theme_txt").text(theme_txt);
toggle_fade('popup_theme', this);
fnStoreSearchSubmit(1);
shuffleList();
}
function fnLocationEnter(){
var sido = $("input[name=sido_c]:checked").val();
var sigungu = $("input[name=sigungu_c]:checked").val();
$("#sido").val(sido);
$("#sigungu").val(sigungu);
var loca_txt = "지역 선택";
if(sido != ""){
switch(sido){
case '경상북도': loca_txt = '경북'; break;
case '경상남도': loca_txt = '경남'; break;
case '전라북도': loca_txt = '전북'; break;
case '전라남도': loca_txt = '전남'; break;
case '충청북도': loca_txt = '충북'; break;
case '충청남도': loca_txt = '충남'; break;
default: loca_txt = sido.substr(0, 2); break;
}
if(sigungu == ""){
loca_txt += " > 전체";
} else {
loca_txt += " > "+sigungu;
}
}
$("#loca_txt").text(loca_txt);
toggle_fade('popup_loca', this);
fnStoreSearchSubmit(1);
shuffleList();
}
function fnSelSido2(sido, sigungu){
$.ajax({
type: "POST",
url: "/sub/ajax.sigungu2.php",
data: {sido : sido, sigungu: sigungu},
cache: false,
async: false,
contentType: "application/x-www-form-urlencoded; UTF-8",
success: function(data){
$("#loca_col_ul_sigungu").html(data);
}
});
}
function fnStoreSearchSubmit(page){
var sido = $("#sido").val();
var sigungu = $("#sigungu").val();
var theme = $("#theme").val();
var stx = $("#stx").val();
var lat = $("#lat_head").val();
var lng = $("#lng_head").val();
$.ajax({
type: "POST",
url: "/sub/ajax.store_list_find.php",
data: {page, lat, lng, sido, sigungu, theme, stx},
cache: false,
async: false,
success: function(data){
$("#store_list_wrap").html(data);
shuffleList(); // 리스트 갱신 후 다시 섞기
}
});
return false;
}
</script>
링크에 url 기재하며, 고수 분들의 조언을 기다립니다!
답변 4개 / 댓글 4개
채택된 답변
+20 포인트
2024-01-28 (일) 18:59:07
Copy
// var storeList = $("#store_list_wrap");
var storeList = $("#store_list_wrap > ul");
답변에 대한 댓글 1개
2024-01-28 (일) 21:30:48
2024-01-28 (일) 18:27:29
제이쿼리는 사용하지 않아서 잘 모르겠고...
바닐라의 경우 아래처럼 cnt_1 부터 cnt_n 까지... n 은 원하는 숫자입니다. <div> 안에 재주껏 내용물을 넣어보세요.
Copy
<div id="cntDiv"></div>
<script>
cnt_1 = "<div>1번 내용</div>";
cnt_2 = "<div>2번 내용</div>";
cnt_3 = "<div>3번 내용</div>";
cnt_4 = "<div>4번 내용</div>";
cnt_5 = "<div>5번 내용</div>";
cnt_6 = "<div>6번 내용</div>";
cnt_7 = "<div>7번 내용</div>";
for (cntTotal = 0; this["cnt_" + (cntTotal + 1)]; cntTotal++);
nA = [];
for (i = 0; i < cntTotal; i++) nA.push(i + 1);
for (j in nA) {
rN = Math.floor(Math.random() * nA.length);
changN = nA[rN];
nA[rN] = nA[j];
nA[j] = changN;
}
for (k of nA) cntDiv.innerHTML += this["cnt_" + k];
</script>
결과물은 https://wittazzurri.com/editor/html_editor.php 에서 확인해 보세요.
답변에 대한 댓글 1개
2024-01-28 (일) 21:33:55
비타주리님 댓글 감사합니다.
말씀하신 바닐라가 무엇인지 잘 모르겠습니다만 나중에 한 번 공부해보겠습니다!!
말씀하신 바닐라가 무엇인지 잘 모르겠습니다만 나중에 한 번 공부해보겠습니다!!
2024-01-28 (일) 17:47:31
추출한 리스트를 자바스크립트로 shuffleList() 하는 작업은 필요 없으며
ajax.store_list_find.php 에서 리스트를 추출하는 쿼리에 ORDER BY RAND() 를 넣어주면 됩니다
// 페이지 로드 시 실행
shuffleList();
위 코드 또한 bbs/list.php에서 $sql_order 에 다음처럼 조건을 주어서 만들면 됩니다
if($bo_table=='free') $sql_order =' order by rand()';
답변에 대한 댓글 1개
블랙캣77
2024-01-28 (일) 17:44:59
페이징이 없고 갯수가 많치가 않다면 리스트 가져 오는 부분 정렬을 랜덤으로 해보세요. 정렬 랜덤으로 하는 방법은 mysql 랜덤이라고 검색해보면 쉽게 찾으실수 있으실거 같습니다.
답변에 대한 댓글 1개
2024-01-28 (일) 18:18:54
블랙캣77님 답변 감사합니다.
매장 리스트가 몇백개 정도 될 거 같은데 알려주신 방법으로 해결이 될지 모르겠네요ㅜㅜ
매장 리스트가 몇백개 정도 될 거 같은데 알려주신 방법으로 해결이 될지 모르겠네요ㅜㅜ
답변을 작성하려면 로그인이 필요합니다.
매번 해결책을 알려주셔서 감사하게도 너무 잘 됩니다.
항상 답변 달아주셔서 너무너무 감사합니다@@@@@!!!!!!!!